I have a dataframe that looks like this:
df <- data.frame(sample = c(1,2,3,4), code = c("D", "B", "A", "B"))
I also have two vectors that look like this:
code <- c("A", "B", "C")
name <- c("Apple", "Bat", "Cat")
I know if I wanted to use the vectors to assign a "name" based on a matching "code" in the dataframe, I could do something like the following:
# This returns the correct output
df$name <- NA
df$name <- ifelse(df$code == code[1], name[1],
ifelse(df$code == code[2], name[2],
ifelse(df$code == code[3], name[3], NA)))
However, I don't want to have to write a new ifelse line for each new entry in the list as it and the dataframe grow/change over time. Is it possible to loop over each code/name pair to assign a value in the dataframe column a bit more dynamically?
Something like this (though this doesn't work):
df$name <- NA
for(i in 1:length(code)) {
for(j in 1:length(name)) {
df$name <- ifelse(df$code == code[i], name[j], NA)
}
}
I've also been looking at Map (also doesn't work):
df$name <- NA
assign_name <- function(code, name, df) {
df$name <- Map(function(code, name) {
ifelse(df$code == code, name, NA)
}, code, name)
return(df)
}
assign_name(code, name, df)
# Error in `$<-.data.frame`(`*tmp*`, name, value = list(A = c(NA, NA, "Apple", :
# replacement has 3 rows, data has 4
I'm struggling to Google this one, feels like I'm missing something simple. Thank you in advance to all the humans out there who are smarter than me.
lut <- setNames(name, code)
df$name <- lut[df$code]