How to combine a larger dataframe with a smaller dataframe in R?

One data frame df contains 72 values corresponding to 4 variables A-D each. Another df2 contains four values corresponding to A-D. I want to combine the two dataframes columnwise such that each row in df has the corresponding value from df2

I was going to use the ifelse function on df for the values. But it’s too tedious to write so many lines of code. Is there an easier way to do this?

library(truncnorm)
x <- c(1:288)
sp <- rep(c("A","B","C","D"), each = 72)

df <- data.frame(x,sp)

x2 <- c(1,2,3,4)
sp <- rep(c("A","B","C","D"), each = 1)

df2 <- data.frame(x2,sp)


#Finaldata set

x  sp  x2
1  A   1
2  A   1
3  A   1
...
288 D 4

>Solution :

Maybe just a left join?

dplyr::left_join(df,df2,by = 'sp')

Leave a Reply