Home > OS >  Making the same adjustment to multiple variables in R
Making the same adjustment to multiple variables in R

Time:11-11

I'm sure this must be quite a basic thing but I'm struggling to find an answer!

I want to know how I can do this kind of thing more efficiently:

data$var1 <- data$var1 %>% str_to_lower()
data$var2 <- data$var2 %>% str_to_lower()
...
data$var99 <- data$var99 %>% str_to_lower()
data$var100 <- data$var100 %>% str_to_lower()

And doing the same with things like:

data %>%
 mutate(var1 = as.numeric(var1),
        var2 = as.numeric(var2),
        ...
        var100 = as.numeric(var100))

It would be really helpful to know how to do this:

  1. With variables that have the same name but are numbered (e.g., v1, v2, v3... v100 - I'm hoping there's a way of selecting all without having to type out every number) and
  2. With variables that have completely different names (e.g., a, b, c... z - presumably I would have to type out each)

...particularly in cases where the variables aren't positioned together in the df (e.g., if variables are a,b,c... and ordered alphabetically, but I just wanted to apply something to variables a, c, d, h, j, s, v).

CodePudding user response:

You can use across matches:

data %>%
  mutate(across(matches("^var[0-9] $"), str_to_lower))

If you have different names then you can use all_of or any_of function. If you want to modify based on variable type use where. For more info use ?language.

  •  Tags:  
  • r
  • Related