简体   繁体   中英

Is it possible to reference a column name with a string?

I've looked up this question before but I can't find a solution to my specific issue.

Essentially, it's very easy to transform datasets by writing something like this -

data %>% transform(x1 = ifelse(x1 == 1, x1 + 50, x1))

But I'm having an issue when I try to replace x1 with the string "x1"

data %>% transform("x1" = ifelse("x1" == 1, "x1" + 50, "x1"))

I've tried using "get", such as get("x1"), but errors are thrown.

Is there any way to do this?

With dplyr , use mutate

library(dplyr)
data %>% 
     mutate(x1 = ifelse(x1 == 1, x1 + 50, x1))

If we pass a character string, either use mutate_at

data %>%
   mutate_at(vars('x1'), ~ ifelse( . == 1, . + 50, .))

Or convert to sym bol and evaluate ( !! )

data %>%
    mutate(!! "x1" := ifelse(!! rlang::sym("x1") == 1, 
          !! rlang::sym("x1") + 50, !!rlang::sym("x1")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM