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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With