【问题标题】:How to perform a rowwise function on an arbitrary of columns? [duplicate]如何对任意列执行逐行函数? [复制]
【发布时间】:2019-01-10 21:39:49
【问题描述】:

我想使用列名而不是索引号对任意一组列执行逐行操作。我知道这可以使用基数 r 和由数字索引的列,但如果我可以使用 tidyverse 管道中的列名来执行此操作,那么对我来说更不容易出错。

这是我正在尝试做的事情的基础。

library(tidyverse)

df <- tibble(name = c("Sam", "Jane", "Erin", "Bert", "Lola"),
             age     = c(11, 10, 11, 12, 10),
             score_a = c(19, 16, 16, 5, 10),
             score_b = c(10, 10, 10, 10, 10))
df %>% 
  rowwise() %>% 
  mutate_at(vars(score_a:score_b),funs(total = sum))
#> Source: local data frame [5 x 6]
#> Groups: <by row>
#> 
#> # A tibble: 5 x 6
#>   name    age score_a score_b score_a_total score_b_total
#>   <chr> <dbl>   <dbl>   <dbl>         <dbl>         <dbl>
#> 1 Sam      11      19      10            19            10
#> 2 Jane     10      16      10            16            10
#> 3 Erin     11      16      10            16            10
#> 4 Bert     12       5      10             5            10
#> 5 Lola     10      10      10            10            10

reprex package (v0.2.1) 于 2019 年 1 月 10 日创建

我实际上想要一张看起来像这样的桌子

#> # A tibble: 5 x 6
#>   name    age score_a score_b  total
#>   <chr> <dbl>   <dbl>   <dbl>  <dbl>
#> 1 Sam      11      19      10    29
#> 2 Jane     10      16      10    27
#> 3 Erin     11      16      10    26
#> 4 Bert     12       5      10    15
#> 5 Lola     10      10      10    20

reprex package (v0.2.1) 于 2019-01-10 创建

【问题讨论】:

  • 您要使用的所有列是否都有一个通用名称?喜欢“score_a”到“score_xy”?
  • 他们没有。我认为@MrFlick 发现了一个类似的问题。它不是超级漂亮,但这看起来就是我想要的。 df %>% mutate(total = select(., score_a:score_b) %>% rowSums)
  • MrFlick 的响应是您正在寻找的东西的类型。 mutate_at 在每一列上执行相同的功能。您正在/正在寻找的是行函数,例如 rowSums
  • @TDP:我在@MrFlick 的原始问题中发布了另一种方法。请看一下。这是我所知道的最干净的解决方案,它不需要在 mutate 内使用 select 或在整个通话过程中使用自引用 .

标签: r dplyr


【解决方案1】:

我认为在 rowwise 函数中使用 grep() 是可能的:

library(tidyverse)

df %>%
 mutate(total_score = rowSums(.[,grep("score_a|score_b", names(.))])) 

  name    age score_a score_b total_score
  <chr> <dbl>   <dbl>   <dbl>       <dbl>
1 Sam     11.     19.     10.         29.
2 Jane    10.     16.     10.         26.
3 Erin    11.     16.     10.         26.
4 Bert    12.      5.     10.         15.
5 Lola    10.     10.     10.         20.

df %>%
 mutate(total_score = rowSums(.[,grep("age|score_b", names(.))])) 

  name    age score_a score_b total_score
  <chr> <dbl>   <dbl>   <dbl>       <dbl>
1 Sam     11.     19.     10.         21.
2 Jane    10.     16.     10.         20.
3 Erin    11.     16.     10.         21.
4 Bert    12.      5.     10.         22.
5 Lola    10.     10.     10.         20.

通过这种方式,您可以选择任意一组列并按列的名称引用这些列。

【讨论】:

    猜你喜欢
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多