Home > Software engineering >  Is there a command to keep the same records from three different dataframes?
Is there a command to keep the same records from three different dataframes?

Time:10-13

I have three different data frame and I would like to create a new one which will contain only the records which exist in a column named id which is the same in every data frame with different records:

Example dataframes:

df1 <- data.frame(id = c("text1","text2","text3","text4","text5",), number1 = c(3,5,3,4,1))
df2 <- data.frame(id = c("text21","text1","text12","text2","text32",), number2 = c(4,3,33,13,11))
df3 <- data.frame(id = c("text12","text32","text1","text21","text2",), number3 = c(11,34,13,11,10))

expected out put:

df_same <- data.frame(id = c("text1","text2"))

CodePudding user response:

We could use Reduce with intersect on a list of vectors

data.frame(id = Reduce(intersect, list(df1$id, df2$id, df3$id)))
  •  Tags:  
  • r
  • Related