如何根据公式字符串创建新变量

编程语言 2026-07-11

如何根据字符串 my_formula1my_formula2mutate新变量?

library(tidyverse)
# sample 1 : this can work ,by the new variable not 'total' ( it's is `eval(str2lang(my_f))`)

my_formula1<- "total = x + 1"
diamonds %>% mutate(eval(str2lang(my_f)))

# sample 2: below code can't work
my_formula2 <- "total = x + y,total2 = y +z"
diamonds %>% mutate(eval(str2lang(my_f2)))

解决方案

这要微妙得多。在这两种情况下,你的输入都会被 mutate() 解释为一个未命名的参数。 在第一个示例中,这仍然有效,因为 mutate() 回退到其默认行为,用表达式的字符串表示来命名新列。 然而,在第二个示例中,它会失败,因为多个表达式被当作一个来处理。

下面给出实现目标的一种方法,使用一个围绕 mutate() 的自定义包装器。

函数

library(tidyverse)

# proposed function
mutate_str <- function(.data, s) {
  # Split on commas
  parts <- stringr::str_split(s, ",")[[1]]

  # Trim whitespace
  parts <- stringr::str_trim(parts)

  # Split each part at the first "="
  kv <- stringr::str_split_fixed(parts, "=", 2)

  # Extract names and expressions
  names <- stringr::str_trim(kv[, 1])
  values <- stringr::str_trim(kv[, 2])

  # Parse RHS into expressions
  exprs <- rlang::parse_exprs(values)

  # Assign names
  exprs <- rlang::set_names(exprs, names)

  dplyr::mutate(.data, !!!exprs)
}

示例1

my_formula1<- "total = x + 1"

diamonds %>% mutate(eval(str2lang(my_formula1)))
#> # A tibble: 53,940 × 11
#>    carat cut       color clarity depth table price     x     y     z
#>    <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#>  1  0.23 Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
#>  2  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
#>  3  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
#>  4  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
#>  5  0.31 Good      J     SI2      63.3    58   335  4.34  4.35  2.75
#>  6  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
#>  7  0.24 Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47
#>  8  0.26 Very Good H     SI1      61.9    55   337  4.07  4.11  2.53
#>  9  0.22 Fair      E     VS2      65.1    61   337  3.87  3.78  2.49
#> 10  0.23 Very Good H     VS1      59.4    61   338  4     4.05  2.39
#> # ℹ 53,930 more rows
#> # ℹ 1 more variable: `eval(str2lang(my_formula1))` <dbl>

diamonds %>% mutate_str(my_formula1)
#> # A tibble: 53,940 × 11
#>    carat cut       color clarity depth table price     x     y     z total
#>    <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl> <dbl>
#>  1  0.23 Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43  4.95
#>  2  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31  4.89
#>  3  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31  5.05
#>  4  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63  5.2 
#>  5  0.31 Good      J     SI2      63.3    58   335  4.34  4.35  2.75  5.34
#>  6  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48  4.94
#>  7  0.24 Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47  4.95
#>  8  0.26 Very Good H     SI1      61.9    55   337  4.07  4.11  2.53  5.07
#>  9  0.22 Fair      E     VS2      65.1    61   337  3.87  3.78  2.49  4.87
#> 10  0.23 Very Good H     VS1      59.4    61   338  4     4.05  2.39  5   
#> # ℹ 53,930 more rows

示例2

my_formula2 <- "total = x + y, total2 = y + z"

diamonds %>% mutate(eval(str2lang(my_formula2)))
#> Error in `mutate()`:
#> ℹ In argument: `eval(str2lang(my_formula2))`.
#> Caused by error in `str2lang()`:
#> ! <text>:1:14: unexpected ','
#> 1: total = x + y,
#>                  ^

diamonds %>% mutate_str(my_formula2)
#> # A tibble: 53,940 × 12
#>    carat cut      color clarity depth table price     x     y     z total total2
#>    <dbl> <ord>    <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl> <dbl>  <dbl>
#>  1  0.23 Ideal    E     SI2      61.5    55   326  3.95  3.98  2.43  7.93   6.41
#>  2  0.21 Premium  E     SI1      59.8    61   326  3.89  3.84  2.31  7.73   6.15
#>  3  0.23 Good     E     VS1      56.9    65   327  4.05  4.07  2.31  8.12   6.38
#>  4  0.29 Premium  I     VS2      62.4    58   334  4.2   4.23  2.63  8.43   6.86
#>  5  0.31 Good     J     SI2      63.3    58   335  4.34  4.35  2.75  8.69   7.1 
#>  6  0.24 Very Go… J     VVS2     62.8    57   336  3.94  3.96  2.48  7.9    6.44
#>  7  0.24 Very Go… I     VVS1     62.3    57   336  3.95  3.98  2.47  7.93   6.45
#>  8  0.26 Very Go… H     SI1      61.9    55   337  4.07  4.11  2.53  8.18   6.64
#>  9  0.22 Fair     E     VS2      65.1    61   337  3.87  3.78  2.49  7.65   6.27
#> 10  0.23 Very Go… H     VS1      59.4    61   338  4     4.05  2.39  8.05   6.44
#> # ℹ 53,930 more rows

创建于2026-03-20,使用 reprex v2.1.1

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章