1

IN R

my data

a <- c('1','2','3','1','1')
b <- c('3','1','2','1','2')
j <- data.frame(a,b)



rowSums(j)                 #error

How can I calculate sum of the row?

1
  • You should be aware of the real classes of the columns in your data. Try str(j) and you'll see that they aren't character class. Apr 14, 2015 at 8:35

1 Answer 1

4

In case you have real character vectors (not factors like in your example) you can use data.matrix in order to convert all the columns to numeric class

j <- data.frame(a, b, stringsAsFactors = FALSE)
rowSums(data.matrix(j))
## [1] 4 3 5 2 3

Otherwise, you will have to convert first to character and then to numeric in order to not lose information

rowSums(sapply(j, function(x) as.numeric(as.character(x))))
## [1] 4 3 5 2 3
1
  • 2
    @DavidArenburg you rock dude! Apr 14, 2015 at 8:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.