Skip to content

Instantly share code, notes, and snippets.

@rhilfi
Created November 30, 2020 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhilfi/6dcef20168b44af1637f9639f196e470 to your computer and use it in GitHub Desktop.
Save rhilfi/6dcef20168b44af1637f9639f196e470 to your computer and use it in GitHub Desktop.
sum_of_some_columns_per_row #R
# Calculate sum of different columns per row
id<-1:5
food<-c(1,4,3,2,1)
drink<-c(4,3,2,4,5)
names<-c("John", "Mick", "Paul","George", "Ringo")
books<-c(3,4,5,4,2)
data<-data.frame(id, food, drink,names, books )
data<-data %>%
mutate(total_sum = select(., food, drink, books) %>% rowSums(na.rm = TRUE)) %>% # variante 1
rowwise() %>%
mutate(total_sum2=sum(food, drink, books)) %>% # variante 2
ungroup() %>% # variante 2
rowwise() %>%
mutate(total_sum3=sum(c_across(where(is.numeric)&!contains("id")&!contains("total")))) %>% # a bit an awkward example of using c_across
ungroup()
# see also: https://dplyr.tidyverse.org/dev/articles/rowwise.html#repeated-function-calls-1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment