简体   繁体   English

如何使用 tidyverse 计算行和

[英]how to compute rowsums using tidyverse

I did mtcars %>% by_row(sum) but got the message:我做了mtcars %>% by_row(sum)但得到了消息:

by_row() is deprecated; by_row()已弃用; please use a combination of: tidyr::nest();请使用以下组合: tidyr::nest(); dplyr::mutate(); dplyr::mutate(); purrr::map()呼噜声::地图()

My naive approach is this我天真的方法是这样的

mtcars %>% 
  group_by(id = row_number()) %>% 
  nest(-id) %>% 
  mutate(hi = map_dbl(data, sum))

Is there a way to do it without creating an "id" column?有没有办法在不创建“id”列的情况下做到这一点?

Is this what you are looking for?这是你想要的?

mtcars %>% mutate(rowsum = rowSums(.))

Output:输出:

    mpg cyl  disp  hp drat    wt  qsec vs am gear carb  rowsum
1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 328.980
2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4 329.795
3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 259.580
4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1 426.135
5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2 590.310
6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1 385.540
7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4 656.920
8  24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2 270.980
9  22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2 299.570
10 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4 350.460
11 17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4 349.660
12 16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3 510.740
13 17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3 511.500
14 15.2   8 275.8 180 3.07 3.780 18.00  0  0    3    3 509.850
15 10.4   8 472.0 205 2.93 5.250 17.98  0  0    3    4 728.560
16 10.4   8 460.0 215 3.00 5.424 17.82  0  0    3    4 726.644

列的子集也可用。

mtcars %>% mutate(rowsum = rowSums(.[2:4]))
mtcars %>% mutate(rowsum = pmap_dbl(., sum))

Furthermore, you can use conditional subsetting, but then you sum up the number of the columns that meet the criterion, not the values:此外,您可以使用条件子集,然后您总结符合条件的列数,而不是值:

mtcars %>%
    select(all_of(c('gear', 'carb'))) %>%
    mutate(
        high_gear_carb = rowSums(. > 3)
    )

   gear carb high_gear_carb
1     4    4              2
2     4    4              2
3     4    1              1
4     3    1              0
5     3    2              0
6     3    1              0
7     3    4              1
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM