rdataframerowwise

How to sum values in a row wise fashion and always selecting all columns apart from first in R


is there a way to select number of columns without explicitly typing the column names. This is more for automation purposes. Consider the following code

a <- c("people", "contracts", "design")
b <- as.numeric(c(1,2,3))
c <- as.numeric(c(2,3,4))
d <- as.numeric(c(5,6,7))

df <- data.frame(cbind(a, b, c, d))

df$b <- as.numeric(df$b)
df$c <- as.numeric(df$c)
df$d <- as.numeric(df$d)

library(dplyr)

df %>% 
  rowwise() %>% 
  mutate(total = sum(b, c, d))

In this example I have added the values of column b, c and d in a row wise fashion. In future exports, there will be columns e, f, g and so on....

Is there a better way to perform this operation as so I don't have to type the columns individually assuming all columns from "b" onwards will always be numeric. It is only column A which is a character.


Solution

  • We could use c_across and automatically detect the numeric columns

    library(dplyr)# version >= 1.1.0
    df %>%
       rowwise %>% 
       mutate(total = sum(c_across(where(is.numeric)))) %>%
       ungroup
    

    It may be better to use rowSums instead of sum with rowwise

    df %>%
       mutate(total = rowSums(pick(where(is.numeric)), na.rm = TRUE))
              a b c d total
    1    people 1 2 5     8
    2 contracts 2 3 6    11
    3    design 3 4 7    14