sum(across(starts_with())) summing all rows also

I would like test to sum the columns for individual rows, not all the rows combined. I also tried across(starts_with(), sum) but that seems to produce all the rows summed for each of the columns instead.

Essentially, how can I achieve testt = c(5, 10)?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(stringr)

df = data.frame(xx_1 = c(1, 2),
                xx_2 = c(1, 2),
                xx_3 = c(1, 2),
                xx_4 = c(1, 2),
                xx_5 = c(1, 2),
                yy_1 = c(3, 4))

df |> mutate(testt = sum(across(starts_with('xx_'))))
#>   xx_1 xx_2 xx_3 xx_4 xx_5 yy_1 testt
#> 1    1    1    1    1    1    3    15
#> 2    2    2    2    2    2    4    15

Created on 2021-12-03 by the reprex package (v2.0.1)

Is this what you want to do?

library(dplyr)

df = data.frame(xx_1 = c(1, 2),
                xx_2 = c(1, 2),
                xx_3 = c(1, 2),
                xx_4 = c(1, 2),
                xx_5 = c(1, 2),
                yy_1 = c(3, 4))

df |> rowwise() |> mutate(testt = sum(c_across(cols = starts_with('xx_'))))
#> # A tibble: 2 x 7
#> # Rowwise: 
#>    xx_1  xx_2  xx_3  xx_4  xx_5  yy_1 testt
#>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1     1     1     1     1     1     3     5
#> 2     2     2     2     2     2     4    10

Created on 2021-12-03 by the reprex package (v2.0.1)

1 Like

Ah of course, so it seems like rowSums is an answer as well
Thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.