Reputation: 13
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.
Upvotes: 1
Views: 35
Reputation: 24845
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")]
Upvotes: 2