R语言 希望使用名称和值循环遍历所有行和列,以运行简单的宏生成器

tv6aics1  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(72)

我使用R来构建一个简单的宏生成器,我想Map一个 Dataframe ,在字符串中进行替换,为 Dataframe 的每一行构建一个输出字符串

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)))


我希望这是有意义的!

omvjsjqw

omvjsjqw1#

如果我理解正确的话,即基于str模式为每行数据创建一个字符串,你可以使用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

字符串

相关问题