0
votes

I have a dataframe df1 with 300+ Columns, and I am trying to subset it to df2 by column names based on a couple dozen inputs in list1. However, some of the items in list1 are not actually column names in df1. So, I get an "undefined columns" error:

df2 <- df1[,list1]
Error in [.data.frame(df1, , list1) :
undefined columns selected

I realize the reason for this error. BUT I can't go through list1 and see which ones occur in df1 and which ones don't. Because I have to do this many many times with many many different lists. Is there a way to simply ignore those (and not include those null column name values from list1 in the subset df2)?

Thanks for your kind help.

2

2 Answers

1
votes

How about something like: df2 <- df1[,list1[list1 %in% names(df1)]]

1
votes

I was hoping for a nicer/shorter) solution for my own use. Here is another

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