R语言 更新/替换表达式

igsr9ssn  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(160)

我想换出一些用户写的代码。表达式就像一个列表,但我不知道如何更新它们。我可以append(),但不能replace()

orig_code <-
  parse(text = 
    "library(tidyverse)   
    list_1 <- list(a = 1, b = 2)"
  )

new_code <- parse(text = "list_1 <- list(a = 1:3)")

# I can append
append(
  x = orig_code,
  values = new_code
)
#> expression(
#>   library(tidyverse), 
#>   list_1 <- list(a = 1, b = 2), 
#>   list_1 <- list(a = 1:3)
#> )

# but not replace
replace(
  x = orig_code,
  list = 2,
  values = new_code
)
#> expression(
#>   library(tidyverse), 
#>   list_1 <- list(a = 1, b = 2)
#> )

# or reassign
orig_code[[2]] <- new_code

orig_code
#> expression(
#>   library(tidyverse), 
#>   list_1 <- list(a = 1, b = 2)
#> )

reprex package(v0.3.0)于2020-07-05创建

4c8rllxm

4c8rllxm1#

一个选项是将其转换为list,然后执行replace项,并将其更改为expression

as.expression(c(replace(
   x = as.list(orig_code),
  list = 2,
   values = as.list(new_code
    ))))
#expression(library(tidyverse), list_1 <- list(a = 1:3))

相关问题