Update R expression

Viewed 83

I want to swap out some code that a user has written. The expressions act like a list but I can't find out how to update them. I can append(), but not 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)
#> )

Created on 2020-07-05 by the reprex package (v0.3.0)

1 Answers

An option is to convert it to list, then do the replacement, and change it to 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))
Related