I have two dataframes, 'a' of dataframe 1 partly overlaps with 'a' of dataframe 2:
df1 <- data.frame('a'=c(1,2,3,4,5,7,8,9,10), 'b'=c(1,20,3,4,50,3,1,7,4), 'c'=c(TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE))
df1
df2 <- data.frame('a'=c(1,2,3,4,5,5,3,2,7, 10:20), 'b'=c(15:34))
df2
And I would like to extract the value 'b' of dataframe 1 for the overlapping values into a new column and add those values (or NA if they don't overlap) to a new column of dataframe 1. I tried the following:
df1$d <- if_else(df2$a %in% df2$a, df1$b, NA)
Error: true
must be length 20 (length of condition
) or one, not 9.
And I tried:
fun1 <- function(x,y) if (y %in% x) {df1[df1$b,]} else {NA}
df1$d <- mapply(fun1, df2$a, df1$a)