How to make sure 3 separate dfs only contain the same columns?

Viewed 68

I have 3 dataframes, all have some overlapping column names, but also some that are not present in at least one column. I am trying to 1) select only columns that are present in all 3 dfs and 2) make sure all of the columns are in the same order (not looking for alphabetical per say).

df1

A     B     C     D
4     5     2     9

df2

A     D     C     F
13    23    94    1

df3

E    C     A     D
3    83    12    7


**Ideal Output**
df1

A     C     D
4     2     9

df2

A     C     D       
13    94    23 

df3

A     C     D
12    83     7

I am honestly not to sure where to start. Intuitively I think something like this:

df1 <- apply(df1, 2, function(x) ifelse(colnames(x) %in% colnames(df2) & colnames(df1) %in% colnames(df3), x, subset(df1, select = -c(x))

Then repeat for the other 2 dfs. Once all three dfs have the same columns, then I would just order it using one of the dfs as a template.

col_order <- colnames(df1)

df2 <- df2[, col_order]

Where am I going wrong?

1 Answers

We can get the datasets in a list, and get the intersecting names and use that to subset

lst1 <- mget(ls(pattern = '^df\\d+$'))
nm1 <- Reduce(intersect, lapply(lst1, names))
lapply(lst1, subset, select = nm1)
Related