Choose variables based on name (simple regular expression)

风格不统一 提交于 2019-11-29 09:29:09

问题


I would like to incorporate variable names that imply what I should do with them. I imagine a dataframe "survey".

library(Rlab) # Needed for rbern() function.
survey <- data.frame(cbind(  
id = seq(1:10),  
likert_this = sample(seq(1:7),10, replace=T),  
likert_that = sample(seq(1:7), 10, replace=T),  
dim_bern_varx = rbern(10, 0.6),  
disc_1 = sample(letters[1:5],10,replace=T)))

Now I would like to do certain things with all variables that contain likert, other things with variables that contain bern etc.

How can this be done in R?


回答1:


You can use grep() with colnames():

survey[,grep("bern", colnames(survey))]



回答2:


If you have a series of names you like to grab you can also use match. perhaps you often need variables "pulse", "exercise", "height", "weight" and "age", but they sometimes show up in different places or with other added variables. You can save the vector of common names then match them against the dataframe and have a new df of just your standard columns in the order you want.

basenames <- c("pulse", "exercise", "height", "weight", "age")
get.columns <- match(basenames, names(dataframe))
new.df <- dataframe[,get.columns]



回答3:


The "operators" package allows some Perl-like syntax:

library(operators)

survey[, colnames(survey) %~% "bern"]

or

subset(survey, select = colnames(survey) %~% "bern")


来源:https://stackoverflow.com/questions/1402634/choose-variables-based-on-name-simple-regular-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!