Select specific columns, where the column names are in another df in r

Viewed 1231

I couldn't find a solution in stack, so here's my issue:

  • I have a df with 342 columns.
  • I want to make a new df with only specific columns
  • The list of columns to keep is in another df, listed in 3 columns titled X,Y,Z for 3 new dataframes

Here's my code right now:

# Read the data:
data <- data.table::fread("data_30_9.csv")


# Import variable names #
variable.names.full = openxlsx::read.xlsx("variables2.xlsx")
Y.variable.names = na.omit(variable.names.full[1])
X.variable.names = na.omit(variable.names.full[2])
Z.variable.names = na.omit(variable.names.full[3])

# Make new DF with only specific columns:
X.Data = data %>% select(as.character(X.variable.names)) # This works as X has only 1 variable
Y.Data = data %>% select(as.character(Y.variable.names)) # This give an error: Error: 
#                                                        # Can't subset columns that don't exist.

Help?

the data is available here:

  1. https://github.com/amirnakar/TammyA/blob/main/data_30_9.csv
  2. https://github.com/amirnakar/TammyA/blob/main/Variables2.xlsx
2 Answers

The problem is that Y.variable.names is a data.frame which you cannot use to subset another data.frame.

You can check by typing class(Y.variable.names).

So the solution to your problem is subsetting Y.variable.names:

Y.Data = data %>% select(Y.variable.names[,1])

Use lapply on variable.names.full and select the columns from data.

list_data <- lapply(variable.names.full, function(x) 
                    data[, na.omit(x), drop = FALSE])
Related