Im working on a dataset which I simplify here.
Suppose I have one data below:
col1 <- c("AAA", "BBB", "CCC")
col2 <- c("auto", "bike", "car")
data1 <- data.frame(col1, col2)
And another data below:
colA <- c("AAA", "BBB", "CCC", "DDD")
colB <- c("1", "2", "3", "4")
data2 <- data.frame(colA, colB)
I would like to add col2 from data1 as another column in data2 that matches colA. I'd like to use ifelse in a loop but im really confused how to do this. Below is my poor attempt.
for(i in data1$col1){
data2$col2 <- ifelse(data1$col1 == i, data1$col2, NA)
}
but im getting this error
Error in $<-.data.frame(*tmp*, "col2", value = c("auto", NA, NA)) :
replacement has 3 rows, data has 4
Im new in loop. Please guide. Thank you.
matchor named vector i.e.data2$col2 <- setNames(data1$col2, data1$col1)[data2$colA]