Skip to content
Prev 390965 / 398506 Next

conditional filling of data.frame - improve code

Heello,

I hadn't posted an answer because my mapply is more complicated that the 
original and much more complicated than Jeff's merge but here it is. But 
if there's a problem with the output of merge, maybe the mapply can be 
of use, only the column expressly named is created.
The result is equal to the original.
I have changed the name exp to exp1.

mydata <- data.frame(sample = c("sample2-2", "sample2-3", "sample1-1", 
"sample1-1", "sample1-1", "sample2-1"))
exp1 <- list(ex1 = c("sample1-1", "sample1-2"), ex2 = c("sample2-1", 
"sample2-2" , "sample2-3"))

for(i in names(exp1)) {
   mydata[mydata[["sample"]] %in% exp1[[i]], "experiment"] <- i
}

# must create the new column beforehand
mydata[["experiment2"]] <- NA_character_
mapply(\(value, name, s){
   i <- which(s %in% value)
   mydata[["experiment2"]][i] <<- name
}, exp1, names(exp1), MoreArgs = list(s = mydata$sample))

mydata
#     sample experiment experiment2
#1 sample2-2        ex2         ex2
#2 sample2-3        ex2         ex2
#3 sample1-1        ex1         ex1
#4 sample1-1        ex1         ex1
#5 sample1-1        ex1         ex1
#6 sample2-1        ex2         ex2


Hope this helps,

Rui Barradas

?s 08:48 de 11/03/2022, Ivan Calandra escreveu: