how to compute rowsums using tidyverse

前端 未结 4 1677
耶瑟儿~
耶瑟儿~ 2020-12-30 14:23

I did mtcars %>% by_row(sum) but got the message:

by_row() is deprecated; please use a combination of: tidyr::nest(); d

相关标签:
4条回答
  • 2020-12-30 14:50

    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
    ...
    
    0 讨论(0)
  • 2020-12-30 15:06
    mtcars %>% mutate(rowsum = pmap_dbl(., sum))
    
    0 讨论(0)
  • 2020-12-30 15:09

    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
    
    0 讨论(0)
  • 2020-12-30 15:17

    Subset of columns is available too.

    mtcars %>% mutate(rowsum = rowSums(.[2:4]))
    
    0 讨论(0)
提交回复
热议问题