How to create new column by summarizing given columns with contains ‘_sales’?
The code as below: the result of md %>% rowwise()%>% mutate(sub_total=across(contains("_sales"),sum)) isn’t what i want.
md$sub_total <- md$a_sales+md$b_sales+md$d_sales can work,but a little complicated when the given columns are more than current
ori_data <- data.frame(a_sales=c(1:5),
tsalses=c(1:5),
b_sales=c(7:11),
d_sales=c(1:5))
# this can't work
md %>% rowwise()%>% mutate(sub_total=across(contains("_sales"),sum))
# this can work, but the code is little boring
md$sub_total <- md$a_sales+md$b_sales+md$d_sales
>Solution :
The issue is with how you are using across. Right now what you are saying is that for every column containing "_sales" you want to do a sum. What you actually want is to sum these columns together.
Instead of using rowwise() and sum() we can simply use rowSums():
ori_data %>%
mutate(sub_total = rowSums(across(contains("_sales"))))