Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: assign dataframe column values using external vectors

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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.

>Solution :

lut <- setNames(name, code)
df$name <- lut[df$code]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading