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.
CodePudding user response:
Try a left_join
like this:
library(dplyr)
left_join(data1, data2, by = c("col1" = "colA"))
# col1 col2 colB
# 1 AAA auto 1
# 2 BBB bike 2
# 3 CCC car 3
Or alternatively:
left_join(data2, data1, by = c("colA" = "col1"))
# colA colB col2
# 1 AAA 1 auto
# 2 BBB 2 bike
# 3 CCC 3 car
# 4 DDD 4 <NA>