2

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
  • 1
    So at the end you want to end up with 3 dataframes? Commented Oct 22, 2020 at 7:04
  • Yes, with 3 dataframes Commented Oct 22, 2020 at 7:23

2 Answers 2

3

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])
Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.