Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Sum of all the columns that start with

Tags:

r

startswith

sum

I want to make a new column that is the sum of all the columns that start with "m_" and a new column that is the sum of all the columns that start with "w_". Unfortunately it is not every nth column, so indexing all the odd and even columns won't work.

columnnames <- c("m_16", "w_16", "w_17", "m_17", "w_18", "m_18")
values1 <- c(3, 4, 8, 1, 12, 4)
values2 <- c(8, 0, 12, 1, 3, 2)
df <- as.data.frame(rbind(values1, values2))
names(df) <- columnnames

What I want to get is:

columnnames <- c("m_16", "w_16", "w_17", "m_17", "w_18", "m_18", "sum_m", "sum_w")
values1 <- c(3, 4, 8, 1, 12, 4, 8, 24)
values2 <- c(8, 0, 12, 1, 3, 2, 11, 15)
df <- as.data.frame(rbind(values1, values2))

names(df) <- columnnames

So far during my search, I only found how to sum specific columns on conditions but I don't want to specify the columns because there's a lot of them.

like image 581
evam Avatar asked Oct 31 '25 07:10

evam


1 Answers

dplyr has a quick answer:

library(dplyr)
df <- df %>% 
    mutate(
        m_col_sum = select(., starts_with("m")) %>% rowSums(),
        w_col_sum = select(., starts_with("w")) %>% rowSums()
    )

You might need to specify na.rm = TRUE as an additional argument to rowSums().

like image 54
bash1000 Avatar answered Nov 02 '25 20:11

bash1000