Undefined columns selected while subsetting df

Lucca Ramalho Source

Let's say i have two diferent df's: details and df

Details

header <- c("header1","header6","header3","header4","header5")
type <- c("type1","type2","type3","type4","type5")

details <- data.frame(header, type)
details
       header  type
    1 Header1 Type1
    2 Header6 Type2
    3 Header3 Type3
    4 Header4 Type4
    5 Header5 Type5

DF

x <- c("test","test","test")
header1 <- x
header2 <- x
header3 <- x

df <- data.frame(header1,header2,header3)
df
  header1 header2 header3
1    test    test    test
2    test    test    test
3    test    test    test

Now i want to join them keeping what's in both of them, so it would come out like this:

  header1 header3
1 test    test
2 test    test
3 test    test

i've tried to do this:

df <- df[details$header]

but it shows me this error message:

Error in `[.data.frame`(df, details$header) : undefined columns selected

What could i do to create a new df keeping only the collumns that exist inside the details$header?

r

Answers

answered 1 week ago akrun #1

The error is mainly due to elements in 'header' column of 'details' that are not the column names. To make it work, use intersect

df[intersect(names(df), as.character(details$header))]
#    header1 header3
#1    test    test
#2    test    test
#3    test    test

answered 1 week ago Onyambu #2

 df[names(df)%in%details[,1]]# df[names(df)%in%details$header]
  header1 header3
1    test    test
2    test    test
3    test    test

comments powered by Disqus