R: Add a column to dateframe using 2 dataframes of unequal length

33 views Asked by At

The goal is to mutate a new column to a df1, by matching a column in both df1 and df2, and returning the matching row value for another column (col5) in df2, [AND ONLY THE VALUE OF THAT COLUMN] which will be added to df1.

    df1 <- data.frame(c(1,1,1,2,2,2,3,3,3), c(9,9,9,8,8,8,7,7,7)), 
       c(6,6,6,5,5,5,4,4,4), c('A','A','A','B','B','B','C','C','C')
    colnames(df1) <- c('col1','col2','col3', 'col4')

    df2 <- data.frame(c(1,2,3), c(100,200,300), c('D','E','F'))
    colnames(df2) <- c('col1','col5', 'col6)

the end result should be

col1 col2 col3 col4 col5
1 9 6 A 100
1 9 6 A 100
1 9 6 A 100
2 8 5 B 200
2 8 5 B 200
2 8 5 B 200
3 7 4 C 300
3 7 4 C 300
3 7 4 C 300

I've tried things like

    df1 <- df1 %>%
       mutate(ifelse(col1==df2$col1, df$2col2, "")

But doesn't work. Suggestions hugely appreciated. left_join almost works, but I am trying to avoid merge all of the columns of the two dataframes. I only want to match col1 in both dataframes, and add col5 from df2 to df1.

0

There are 0 answers