我有使用的变量列表及其相应的定义。我还提供了公式,但我希望翻译公式(示例中提供)以更好地理解他们在说什么。我的示例很简单,但通常有大约 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))
定义一个函数
subst
其中
因此使用最后注释中的输入
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>