I have two dataframes:
DF1 <- data.frame (col1 = c("a", "b", "c"),
col2 = c("4", "3", "6")
)
DF2 <- data.frame (col3 = c("x", "y", "z"),
col4 = c("18", "3", "5")
)
DF1
col2 col2
1 a 4
2 b 3
3 c 6
DF2
col3 col4
1 x 18
2 y 3
3 z 5
For each row I want to add DF2$col3 to DF1, if DF2$col4 has the same value as DF1$col2.
Same value <- copy x/y/z to new column in DF1
Different value <- write NA to new column in DF1
How can I do this?
CodePudding user response:
Is this what you need?
DF1$new <- ifelse(as.numeric(DF1$col2) == as.numeric(DF2$col4),
DF2$col3,
NA)
Result:
DF1
col1 col2 new
1 a 4 <NA>
2 b 3 y
3 c 6 <NA>
CodePudding user response:
This is a merge operation.
merge(DF1, DF2, by.x="col2", by.y="col4", all.x = TRUE)
# col2 col1 col3
# 1 3 b y
# 2 4 a <NA>
# 3 6 c <NA>
Or a match
operation:
DF1$col3 <- DF2$col3[match(DF2$col4, DF1$col2)]
DF1
# col1 col2 col3
# 1 a 4 <NA>
# 2 b 3 y
# 3 c 6 <NA>
CodePudding user response:
library(tidyverse)
DF1 %>%
left_join(., DF2, by = c('col2' = 'col4'))
which gives
# col1 col2 col3
# 1 a 4 <NA>
# 2 b 3 y
# 3 c 6 <NA>