如何用变量的定义替换公式中的变量?

问题描述 投票:0回答:1

enter image description here我有使用的变量列表及其相应的定义。我还提供了公式,但我希望翻译公式(示例中提供)以更好地理解他们在说什么。我的示例很简单,但通常有大约 100 个变量和 100 个公式。 (图中,公式列中的“cel”应更正为“ccel”)

我试图找到类似的问题,但找不到答案。

structure(list(variable = c("cs", "csp", "cb", "cc", "ccel", 
"ccrt"), definition = c("cost of salad", "cost of soup", "cost of bread", 
"cost of chicken", "cost of celery", "cost of carrot"), formula = c("cs=cb+ccel+cc", 
"csp=cc+ccel+crt", NA, NA, NA, NA), Translation = c("cost of salad=cost of bread+cost of celery+cost of chicken", 
"cost of soup=cost of chicken+cost of celery+cost of carrot", 
NA, NA, NA, NA)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-6L))
r variables replace
1个回答
0
投票

定义一个函数

subst
其中

  • 输入表达式字符向量 expr 并将其转换为语言对象 expr2
  • 将数据框 DF 的前两列转换为名称列表 defs2
  • 使用替换执行替换
  • 使用 deparse1 转换回字符向量
  • 删除上述过程生成的反引号
  • 将“NA”转换为 NA

因此使用最后注释中的输入

subst <- function(expr, defs) {
  expr2 <- lapply(expr, str2lang)
  defs2 <- defs[1:2] |> deframe() |> as.list() |> lapply(as.name)
  s <- sapply(expr2, \(expr) deparse1(do.call(substitute, list(expr, defs2))))
  ifelse(s == "NA", NA, s)
}

# test run
DF %>%
  mutate(translation = subst(formula, pick(variable, definition)))

给予

# A tibble: 6 × 4
  variable definition      formula        translation                           
  <chr>    <chr>           <chr>          <chr>                                 
1 cs       cost of salad   cs=cb+ccel+cc  cost of salad = cost of bread + cost …
2 csp      cost of soup    csp=cc+cel+crt cost of soup = cost of chicken + cel …
3 cb       cost of bread   <NA>           <NA>                                  
4 cc       cost of chicken <NA>           <NA>                                  
5 ccel     cost of celery  <NA>           <NA>                                  
6 ccrt     cost of carrot  <NA>           <NA>                                  
© www.soinside.com 2019 - 2024. All rights reserved.