0

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)
  • 1
    I think this is a merge/join operation. Please include (manually) your expected output into `df1`, perhaps as an already-made column (so that we can reproduce in code). – r2evans Jan 06 '22 at 12:54
  • Possible duplicate https://stackoverflow.com/q/1299871/680068 – zx8754 Jan 06 '22 at 13:10
  • user17850272, see the dupe-links for good discussions on the merge process. If it does not resolve your issues (perhaps just `merge(df1, df2, by = "a")`, not sure), then you'll need to [edit] your question and provide the expected output and code you've attempted. Once that's done, @ping me and I can reopen the question to resolve issues. Good luck! – r2evans Jan 06 '22 at 14:06

0 Answers0