3

I have a vector of names:

nums = 1:5
names = paste("name_", nums, sep="")

And a data frame where col1 contains a subset of the values listed in names:

Name    Count
name_1  14
name_3  2
name_5  11

I would like to use the vector of names to add rows to the data frame for names that are currently missing from the data frame, so that the final product looks like this:

Name    Count
name_1  14
name_2  0
name_3  2
name_4  0
name_5  11

I've come across some other variations of this question, but can't seem to find a solution that matches my scenario. Thanks for any help!

3 Answers 3

4

One option is complete

library(tidyr)
complete(df1, Name = names, fill = list(Count = 0))
# A tibble: 5 x 2
#  Name   Count
#  <chr>  <dbl>
#1 name_1    14
#2 name_2     0
#3 name_3     2
#4 name_4     0
#5 name_5    11

data

df1 <- structure(list(Name = c("name_1", "name_3", "name_5"), Count = c(14L, 
2L, 11L)), class = "data.frame", row.names = c(NA, -3L))
Sign up to request clarification or add additional context in comments.

Comments

3

You can merge and then replace the NAs resulting from non-matches with 0

out <- merge(df, data.frame(Name = names), all = TRUE)
out$Count <- with(out, replace(Count, is.na(Count), 0))

out
#     Name Count
# 1 name_1    14
# 2 name_2     0
# 3 name_3     2
# 4 name_4     0
# 5 name_5    11

Comments

3
data.frame(names, Count = pmax(df1$Count[match(names, df1$Name)], 0, na.rm = TRUE))
#   names Count
#1 name_1    14
#2 name_2     0
#3 name_3     2
#4 name_4     0
#5 name_5    11

1 Comment

Huh, so R does have a built-in coalesce function, it's just hidden in a max function. Never would have guessed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.