我正在使用 R 构建一个简单的宏生成器,并且 我想映射整个数据框,在字符串构建中进行替换 数据帧的每一行都有一个输出字符串
library(tidyverse)
df<-tribble(
~title, ~name,~age,
"Mr","Smith",46,
"Ms","Jones",26,
"Ms","Wiles",20
)
str<-"
This has parameters {{title}} {{name}}
and more {{age}}
"
我需要为数据帧的每一行应用 gsub 函数,并且 子匹配列的参数名称的值
fun<-function(name-of-column,value-of-column) {
gsub("\\{name-of-column\\}",value-in-column,str)
}
排列列数据很容易
df %>% mutate(across(where(is.character),~ gsub("mit","yyy",.x)))
但是我想对外面的东西进行操作并传递名称和 操作 .x 的列值给出 tibble 中的值 但是a怎么指代这个名字呢?
df %>% mutate(across(where(is.character),~ fun(.x,.x)))
我希望这是有道理的!
如果我理解正确,您可以使用
glue::glue
来实现您想要的结果,如下所示:
library(tidyverse)
df <- tribble(
~title, ~name, ~age,
"Mr", "Smith", 46,
"Ms", "Jones", 26,
"Ms", "Wiles", 20
)
str <- "
This has parameters {{title}} {{name}}
and more {{age}}
"
df %>%
mutate(
output = glue::glue(str, .open = "{{", .close = "}}")
)
#> # A tibble: 3 × 4
#> title name age output
#> <chr> <chr> <dbl> <glue>
#> 1 Mr Smith 46 This has parameters Mr Smith
#> and more 46
#> 2 Ms Jones 26 This has parameters Ms Jones
#> and more 26
#> 3 Ms Wiles 20 This has parameters Ms Wiles
#> and more 20