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

Is there a way to use get row sums with specified variables

I would like to get the sum rows but excluding a given row. Listing all the variables is a bit tedious. I would like to highlight by position the variable to exclude in the operation. Any idea?

library(tidyverse)


df <- tribble(
  ~"var1", ~"var2", ~"var3", ~"var4",
  "A", 20, 10, 23, 
  "B", 30, 6, 34, 
  "C", 40, 8, 23, 
  "D", 50, 10, 24
  
)

# This is the desired output 
df %>% 
  rowwise() %>% 
  mutate(total = sum(var2, var3, var4))

>Solution :

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

You could use base R:



df$total <- rowSums(df[, 2:4])

df

#> # A tibble: 4 x 5
#>   var1   var2  var3  var4 total
#>   <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 A        20    10    23    53
#> 2 B        30     6    34    70
#> 3 C        40     8    23    71
#> 4 D        50    10    24    84

Created on 2022-02-05 by the reprex package (v2.0.1)

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