[英]R: Rename R objects in an expression
我有一个表达式(有时很简单,有时更复杂),我正在寻找一种强大的方法来重命名表达式中的对象。 我目前正在将表达式转换为字符串,进行一些匹配和替换。 但这肯定不是最防错的方法。
本质上,我认为类似于 RStudio 的“在范围内重命名”功能,但能够以编程方式在单个表达式上运行它。
我认为有一种方法可以将表达式分解成各个部分,重命名,然后重新组装?
谢谢!
library(rlang)
# what i have
expr(row_type == 'label')
#> row_type == "label"
# what i want
expr(row_type_2 == 'label')
#> row_type_2 == "label"
# can it also work with `.data$` prefix to give us `.data$row_type_2 == 'label'`
expr(.data$row_type == 'label')
#> .data$row_type == "label"
如图所示使用substitute
:
e <- expr(row_type == 'label')
do.call("substitute", list(e, list(row_type = as.name("row_type_2"))))
## row_type_2 == "label"
e2 <- expr(.data$row_type == 'label')
do.call("substitute", list(e2, list(row_type = as.name("row_type_2"))))
## .data$row_type_2 == "label"
如果您知道 e 和 e2 的精确结构,这也有效:
e[[3]] <- as.name("row_type_2")
e
## row_type == row_type_2
e2[[2:3]] <- as.name("row_type_2")
e2
## .data$row_type_2 == "label"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.