R dplyr: rowwise + mutate (+glue) - 如何 get/refer 行内容?

R dplyr: rowwise + mutate (+glue) - how to get/refer row content?

输入数据的简单例子:

dataset <- data.frame("part1" = c("a", "b", "c"),
                       "part2" = c("x", "y", "z"),
                       "caption" = c("{part1} {part2}",
                                     "{part2} {part1}",
                                     "{part2} {part1} {part2}"),
                       stringsAsFactors = F)

预期结果:

# A tibble: 3 x 3
  part1 part2 caption
  <chr> <chr> <chr>  
1 a     x     a x    
2 b     y     y b    
3 c     z     z c z  

下面的代码不起作用,因为.指的是整个dataset,而不是整行内容的数据:

dataset %>%
  rowwise() %>%
  mutate("caption" =
           glue::glue_data(., caption)
         )

问题:如何将行(所有)内容传递给glue

有效的代码(行 "content" 明确声明)不是我一直在寻找的代码,因为在我的数据集中 caption "pattern" 中使用了更多的列,因此我想避免手动声明它,只需传递整行内容。

dataset %>%
  rowwise() %>%
  mutate("caption" =
           glue::glue_data(
             list("part1" =  part1,
                  "part2" = part2)
             , caption)
  )

它的工作原理如下:

dataset %>% rowwise %>% mutate(r=as.character(glue(caption)))
#Source: local data frame [3 x 4]
#Groups: <by row>

## A tibble: 3 x 4
#  part1 part2 caption                 r    
#  <chr> <chr> <chr>                   <chr>
#1 a     x     {part1} {part2}         a x  
#2 b     y     {part2} {part1}         y b  
#3 c     z     {part2} {part1} {part2} z c z

注意:我添加 as.character 只是为了避免似乎是 rowwise(Vectorizing 'glue' elements may not preserve their attributes)

的警告