R dplyr:逐行+变异(+ glue)-如何获取/引用行内容? [英] R dplyr: rowwise + mutate (+glue) - how to get/refer row content?

查看:102
本文介绍了R dplyr:逐行+变异(+ glue)-如何获取/引用行内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入数据的简单示例:

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,而不是整个行内容的数据:

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

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

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

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

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

推荐答案

它的工作原理如下:

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)

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)

这篇关于R dplyr:逐行+变异(+ glue)-如何获取/引用行内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆