How to use strings as parameters in R

2

Galera,

I need to create a column using a string and use other column strings as arguments, for example:

dataframe <- dataframe %>% mutate("Newstring" = case_when("stringA" < 65 & stringB == 0 ~ 1, TRUE ~ 0))

I believe parsing or eval, or even the combination of the two, can help with this task.

Can you help?

Sincerely, Arduin

    
asked by anonymous 26.05.2018 / 18:36

1 answer

2

The best place to understand how to use strings in place of variable names is this Programming with dplyr .

You need to do something much like parse and eval that you quoted, but dplyr , provides through the rlang package, a more intuitive way. It is worth reading the rlang site.

Suppose you have two strings representing variable names:

x <- "nova_coluna"
y <- "hp"

You can create a new column called nova_coluna that equals the hp variable as follows:

library(dplyr)
library(rlang)

y <- sym(y)

mtcars %>%
  mutate(!! x := !!y)

Note that we do not use = , because !!x = !!y is not a syntactically valid code. We used the sym function to transform a string into a symbol, so dplyr would look like a variable name.

    
28.05.2018 / 13:41