3
votes

I have a data.frame

DF1
a.x.c b.y.l c.z.n d.a.pl f.e.cl

which consists of numeric columns

I also have a list

DF2
a.x.c  c.z.n  f.e.cl

which contains certain names of columns in DF2

I need to create DF3 that would store only those columns of DF1 which have matching names in DF2. I have tried which to find indexes of columns i need. But problem that i have long name list of columns and which become useless.

Could you please help. Thank you beforehand.

1
Can you update the post with the str(DF1) and str(DF2)akrun

1 Answers

5
votes

We can use intersect to get the names that are common in both the datasets and use that to subset the columns of 'DF1' to create 'DF3'.

DF3 <- DF1[intersect(names(DF1),names(DF2))]
DF3
#  a.x.c c.z.n
#1     1     7
#2     2     8
#3     3     9

data

DF1 <- data.frame(a.x.c = 1:3, b.y.l= 4:6, c.z.n=7:9)
DF2 <- list(a.x.c= 1:5, c.z.n=8:15, z.l.y=22:29)