Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose variables based on name (simple regular expression)

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?

like image 455
Andreas Avatar asked Sep 09 '09 23:09

Andreas


People also ask

How do you name a variable in RegEx?

The first character of the variable name must either be alphabet or underscore. It should not start with the digit. No commas and blanks are allowed in the variable name. No special symbols other than underscore are allowed in the variable name.

Why * is used in RegEx?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"

What does /[ (] regular expression indicate?

What does /[^(]* regular expression indicate? Explanation: The [^…] character class is used to match or draw any one character not between the brackets.

How do you specify in RegEx?

You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets, it is taken as a literal hyphen to be included in the character class as a normal character. For example, [^abc] is the same as [^a-c] .


2 Answers

You can use grep() with colnames():

survey[,grep("bern", colnames(survey))]
like image 173
Shane Avatar answered Nov 04 '22 22:11

Shane


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]
like image 31
kpierce8 Avatar answered Nov 04 '22 21:11

kpierce8