1

I have a data frame (mydata) with >200 variables. I would like to automatically subset some of them into a smaller data frame.

The name of the variables I would like to subset follow a naming convention, e.g., "Q1Pct", "Q2Pct", ... "Q18Pct".

I can get a list of the variables using:

Q.names <- setNames(as.list(1:18),paste(paste0("mydata$Q",1:18,"Pct")))

I have tried to combine the list into a new data frame, but it isn't working:

df.QList <- data.frame(Q.names)

I'm sure there is a much better way to do this - please help.

1 Answer 1

2

You can try this:

library(dplyr)

select(mydata, all_of(paste0("Q",1:18,"Pct")))

Or, more simply (base R):

mydata[,paste0("Q",1:18,"Pct")]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much langtang - you're a legend! That works perfectly!

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.