rdplyrrowsum

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

  • 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)