2

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.

benson23
  • 16,369
  • 9
  • 19
  • 38
TheBoomerang
  • 109
  • 5
  • 1
    Don't use `data.frame(cbind(a, b, c, d))` to create a dataframe. If the columns have different types, `cbind` forces all of them into the same type. – Darren Tsai Apr 26 '23 at 13:48

2 Answers2

2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
2

If you are sure the first column will always be excluded, you can use a single rowSums for that.

df$Total <- rowSums(df[, -1])

          a b c d Total
1    people 1 2 5     8
2 contracts 2 3 6    11
3    design 3 4 7    14
benson23
  • 16,369
  • 9
  • 19
  • 38