We don't have to remove non numeric columns. We just need to make sure we aren't summing non numeric columns (character, factor, logical for example). sum(2, "c")
will give us an error for this reason. If we have a column of logical type sum
will treat FALSE
as 0 and TRUE
as 1. See ?sum
for more info.
With base R as @DavidArenburg mentions, we can do:
df$row_sum <- rowSums(df[-1])
df
name X1day X2day X3day row_sum
1 a 20 30 40 90
2 b 30 10 0 40
3 c 12 5 3 20
If we have other columns that aren't numeric and shouldn't be summed, we can use sapply
to only sum rows of columns that are numeric:
df$row_sum <- rowSums(df[, sapply(df, is.numeric)])
df
name X1day X2day X3day row_sum
1 a 20 30 40 90
2 b 30 10 0 40
3 c 12 5 3 20
This would be useful when removing the first column isn't enough. For example, if there is a forth column that is of character type.
@Jaap also mentioned another base R solution using Reduce
:
Reduce('+', df[,-1])
# again, if removing the first column isn't enough we can do
Reduce('+', df[, sapply(df, is.numeric)])
Alternatively, with dplyr
:
library(dplyr)
df %>%
rowwise() %>%
mutate(row_sum = sum(X1day, X2day, X3day))
# A tibble: 3 x 5
name X1day X2day X3day row_sum
<chr> <int> <int> <int> <int>
1 a 20 30 40 90
2 b 30 10 0 40
3 c 12 5 3 20
Data:
df <- read.table(text = "name 1day 2day 3day
a 20 30 40
b 30 10 0
c 12 5 3", header = TRUE, stringsAsFactor = FALSE)