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?
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.
- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"
What does /[^(]* regular expression indicate? Explanation: The [^…] character class is used to match or draw any one character not between the brackets.
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] .
You can use grep()
with colnames()
:
survey[,grep("bern", colnames(survey))]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With