Multiple identical columns in multiple data frames - R

Viewed 149

I have four data frames with one similar column named "Type".

df1 <- data.frame(Type = c('A','B','C','D','E','F'))
df2 <- data.frame(Type = c('A','B','C','D','E','F'))
df3 <- data.frame(Type = c('A','B','C','D','E','F'))
df4 <- data.frame(Type = c('A','Z','C','D','E','F'))

I would like to check if this column is identical over all data frames.

At the moment I'm checking two data frames at a time by using this:

as.integer(as.logical(identical(df1$Type, df2$Type)))

Which gives me 1 if identical and 0 if not.

I would like to perform a single line such as this:

as.integer(as.logical(identical(df1$Type, df2$Type, df3$Type, df4$Type)))

But identical can only handle 2 columns at once.

I also found this Testing for multiple identical columns in R, but this only applies for columns in one data frame.

1 Answers

You can use extract the Type column from the dataframes and compare any one element with all of them.

list_df <- mget(paste0('df', 1:4))
#Or manually creating a list
#list_df <- list(df1, df2, df3, df4)

tmp <- lapply(list_df, `[[`, 'Type')
all(sapply(tmp, function(x) all(x == tmp[[1]])))
#[1] FALSE
Related