some of the suuggestd solutions. However, first, as always, creating some date,
dta <- structure(list(name = structure(1:3, .Label = c("abc", "def",
"ert"), class = "factor"), state = structure(c(3L, 1L, 2L), .Label = c("ka",
"pn", "rt"), class = "factor"), num1 = c(10L, 20L, 30L), num2 = c(40L,
50L, 60L), num3 = c(8L, 15L, 16L)), .Names = c("name", "state",
"num1", "num2", "num3"), class = "data.frame", row.names = c(NA,
-3L))
Second, almost always, show the data,
dta
#> name state num1 num2 num3
#> 1 abc rt 10 40 8
#> 2 def ka 20 50 15
#> 3 ert pn 30 60 16
maybe also use str()
as it's relevant to understand the spciac problem here,
str(dta)
#> 'data.frame': 3 obs. of 5 variables:
#> $ name : Factor w/ 3 levels "abc","def","ert": 1 2 3
#> $ state: Factor w/ 3 levels "ka","pn","rt": 3 1 2
#> $ num1 : int 10 20 30
#> $ num2 : int 40 50 60
#> $ num3 : int 8 15 16
The problem originate in that the data is a mix of factors and integers, obliviously we cannot sum factors
Now to some solutions.
First, akrun's first solution,
rowSums(dta[grep("num\\d+", names(dta))])
#> [1] 58 85 106
Second, Renu's solution,
rowSums(dta[,sapply(dta, is.numeric)])
#> [1] 58 85 106
Third, a slightly reword version of akrun's second solution,
# install.packages(c("tidyverse"), dependencies = TRUE)
library(tidyverse)
dta %>% select(matches("num\\d+")) %>% mutate(rowsum = rowSums(.))
#> num1 num2 num3 rowsum
#> 1 10 40 8 58
#> 2 20 50 15 85
#> 3 30 60 16 106
Finally, this nice plyr option,
# install.packages(c("plyr"), dependencies = TRUE)
plyr::numcolwise(sum)(dta)
#> num1 num2 num3
#> 1 60 150 39
Finally, here a almost identical question. Now they are at lest linked.