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
Collapse/Concatenate/Aggregate a Column to a Single Comma Separated String Within Each Group
How to Convert a Factor to Integer\Numeric Without Loss of Information
Reshaping Multiple Sets of Measurement Columns (Wide Format) into Single Columns (Long Format)
Order Bars in Ggplot2 Bar Graph
Transpose/Reshape Dataframe Without "Timevar" from Long to Wide Format
Sort (Order) Data Frame Rows by Multiple Columns
Error: Could Not Find Function ... in R
Ggplot With 2 Y Axes on Each Side and Different Scales
Numbering Rows Within Groups in a Data Frame
How to Deal With "Package 'Xxx' Is Not Available (For R Version X.Y.Z)" Warning
Simultaneously Merge Multiple Data.Frames in a List
Mean Per Group in a Data.Frame
Split Data Frame String Column into Multiple Columns
Repeat Each Row of Data.Frame the Number of Times Specified in a Column