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

别等时光非礼了梦想. 提交于 2020-01-25 00:38:08

问题


The simple example of input data:

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

Expected results:

# 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  

The below code doesn't work, because . refers to the whole dataset, instead of data of the whole row content:

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

Question: how to pass row (all) content to glue?

The code that works (row "content" declared explicitly) is not what I've been looking for, because there are more columns used in caption "pattern" in my data set, thus I would like to avoid to declare it manually, just pass the whole row content.

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

回答1:


It works simply as:

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

NOTE : I added the as.characteronly to avoid warnings that seem to be an issue with rowwise(Vectorizing 'glue' elements may not preserve their attributes)



来源:https://stackoverflow.com/questions/52403164/r-dplyr-rowwise-mutate-glue-how-to-get-refer-row-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!