Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: colSums when not all columns are numeric

Tags:

r

I have the following data frame

Type   CA   AR
alpha   1   5  
beta    4   9 
gamma   3   8 

I want to get the column and row sums such that it looks like this:

    Type   CA   AR Total
    alpha   1   5    6
    beta    4   9    13
    gamma   3   8    11
    Total   8   22   30

I am able to do rowSums (as shown above) I guess because they are all numeric.

colSums(df)

However, when I do colSums I get the error 'x must be numeric.' I realize that this is because the "Type" column is not numeric.

If I do the following code such that I try to print the value into the 4th row (and only the 2nd through 4th columns are summed)

df[,4] = colSums(df[c(2:4)]

Then I get an error that replacement isn't same as data size.

Does anyone know how to work around this? I want to print the column sums for columns 2-4, and leave the 1st column total blank or allow me to print "Total"?

Thanks in advance!!

like image 905
user4918087 Avatar asked Dec 03 '22 17:12

user4918087


2 Answers

Checkout numcolwise() in the plyr package.

library(plyr)

df <- data.frame(
  Type = c("alpha", "beta", "gamme"),
  CA = c(1, 4, 3),
  AR = c(5, 9, 8)
)

numcolwise(sum)(df)

Result:

  CA AR
1  8 22
like image 199
aaronwolen Avatar answered Dec 22 '22 20:12

aaronwolen


Use a matrix:

m <- as.matrix(df[,-1])
rownames(m) <- df$Type
#       CA AR
# alpha  1  5
# beta   4  9
# gamma  3  8

Then add margins:

addmargins(m,FUN=c(Total=sum),quiet=TRUE)
#       CA AR Total
# alpha  1  5     6
# beta   4  9    13
# gamma  3  8    11
# Total  8 22    30

The simpler addmargins(m) also works, but defaults to labeling the margins with "Sum".

like image 45
Frank Avatar answered Dec 22 '22 21:12

Frank