Reputation: 423
I have two dataframes with differenth lengths. On is a sample and the other a test sample
df1 a b c d ...
1 0 0 0
2 0 0 1
df2 a e b c d ...
1 1 0 0 0
2 0 0 0 1
How can I delete the columns of df2 not in common with df1 ? As a result I'm looking for df2 with the same columns as df1 (a, b, c, d ...). I tried merge() but its not what i'm looking for.
Upvotes: 0
Views: 2398
Reputation: 101
If I understand your question correctly you can subset by the column-names like this:
df2[, colnames(df1)]
If you have column names in df1 not present in df2 you can do
df2[, intersect(colnames(df1), colnames(df2))]
Edit: forgot a comma
Upvotes: 4