Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create new column by summarizing given columns with contains '_sales' in a smart way?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading