Adding a row to a data frame while saving the class of each column

I would like to add a row to the data frame displaying the totals of the column.

test = data.frame('name' = c('a','b','c'),'x' = c(1,2,3),'y' = c(1,2,3))
class(test[,2])
[1] "numeric"

test = rbind(test,c('Total',apply(test[,-1],2,sum)))
   name x y
1     a 1 1
2     b 2 2
3     c 3 3
4 Total 6 6

class(test[,2])
[1] "character"

I need the numeric columns to remain numeric. I understand that this is because the mixed vector that I am trying to add is actually a symbolic character. What good is this? I tried rbind with a list, but it did not work with the apply function.

Thanks in advance

+3
source share
2 answers

This line should be a list of three elements with names. Also, your first column is a factor factor, so you either need to deal with this or not make it a factor:

test = data.frame('name' = c('a','b','c'),
 'x' = c(1,2,3),
 'y' = c(1,2,3),
 stringsAsFactors=FALSE)
 test = rbind(test,c(name='Total',as.list(apply(test[,-1],2,sum))))
+1
source

You can do it your way, and then just change these columns to numeric.

test[,2:3] <- sapply(test[,2:3], as.numeric)
0
source

All Articles