How to Get Rowsums for Selected Columns in R

How to get rowSums for selected columns in R

Here is a quite simple solution using apply.

output <- data.frame( x1 = apply(data[2:4], 1, sum) ,
x2 = apply(data[5:7], 1, sum) )

result:

output
> x1 x2
> 1 14 13
> 2 66 18
> 3 8 12
> 4 100 24

How to calculate row sums or counts on selected columns with condition using tidyverse?

We can use mutate_at to replace the value based on the condition (1, 2, 6) with TRUE or FALSE, use rowSums, and then bind to the original data frame.

library(dplyr)

rp.pptn2 <- rp.pptn %>%
mutate_at(vars(3:11), funs(. %in% c(1, 2, 6))) %>%
transmute(pptnlow = rowSums(.[, 3:11])) %>%
bind_cols(rp.pptn, .)

sum cells of certain columns for each row

You could do something like this:

summed <- rowSums(zscore[, c(1, 2, 3, 5)])

rowsum across specific columns using dplyr's start_with

Using just dplyr, you can do:

data %>%
mutate(hc_agg = rowSums(select(., starts_with("hc"))))

name hc_1 hc_2 ur_1 ur_2 hc_agg
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Ash 1 2 1 3 3
2 Ashley 2 2 5 4 4
3 Ashton 3 2 5 3 5


Related Topics



Leave a reply



Submit