How to use strings as parameters in R

Asked

Viewed 119 times

2

Galley,

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 that parse or Eval, or even the combination of the two, can help in this task.

Can help?

Sincerely yours truly, Arduin

  • get("stringA") works. As for "Newstring", I believe only by changing the name of the column a posteriori.

1 answer

2


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

It is necessary to do something very similar to parse and eval that you quoted, but the dplyr, provides through the package rlang, a more intuitive way. It is worth reading also the website of rlang.

Suppose you have two strings representing variable names:

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

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

library(dplyr)
library(rlang)

y <- sym(y)

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.