Sharon Soler
Sharon Soler

Reputation: 109

Compare column names of two data frames. If matching, extract row values

I'm currently trying to compare the column names of two data frames (ex. df1 and df2) and extract the values from one of them (df2), if there is a match, to create a new (third) data frame.

Example,

df1 <- data.frame(x3=469, x4=465, x7=501, x10=467, x12=459)
df2 <- data.frame(x3="IL_NA1A_P", x4="IL_NA3D_P", x5="PROD005_P", x6="PROD008_P", 
                  x7="PROD009_P", x8="PROD010_P", x9="PROD012_P", x10="PROD014_P",
                  x11="PROD021_P", x12="PROD023A_P")

I am expecting the output to be more along with the following,

x3  x4  x7 x10 x12
IL_NA1A_P IL_NA3D_P PROD009_P PROD014_P PROD023A_P

Any help would be appreciated.

Upvotes: 0

Views: 1559

Answers (3)

akrun
akrun

Reputation: 886938

We can also use

library(dplyr)
df2 %>%
    select_at(vars(names(df1))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388807

If all of df1 column names are present in df2 you can use -

df2[names(df1)]

#         x3        x4        x7       x10        x12
#1 IL_NA1A_P IL_NA3D_P PROD009_P PROD014_P PROD023A_P

If only few of df1 column names are present in df2 you can either use -

df2[intersect(names(df2), names(df1))]

Or in dplyr.

library(dplyr)
df2 %>%  select(any_of(names(df1)))

Upvotes: 0

Cettt
Cettt

Reputation: 11981

this would work:

df2[, colnames(df2) %in% colnames(df1)]
    x3        x4        x7       x10        x12
1 IL_NA1A_P IL_NA3D_P PROD009_P PROD014_P PROD023A_P

You simply check which column-names of df2 appear also in df1 and select these columns from df2.

Upvotes: 3

Related Questions