1

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

Moses
  • 1,391
  • 10
  • 25

2 Answers2

2

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)

Peter
  • 11,500
  • 5
  • 21
  • 31
2

Here is a dplyr solution that uses select:

df %>% 
  mutate(total = rowSums(select(., -var1))) 
  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
TarJae
  • 72,363
  • 6
  • 19
  • 66