Vishan Rana
Vishan Rana

Reputation: 367

How to add sum of column in third row

I want to add sum of till_5 as Grand total in last with new row. I'm trying colSums but it shows error as mentioned.

df1=rbind(df1,c("Grand Total",colSums(df1[,3],na.rm = T)))
#Error in colSums(df1[, 3], na.rm = T) : 
#  'x' must be an array of at least two dimensions

data set (df1)

origin  destination_city2   till_5
A   Chennai 72
B   Coimbatore  4
C   Jaipur  1
D   Ajmer   3
E   Jaipur  4
F   Kishangarh  1

Upvotes: 1

Views: 107

Answers (2)

akrun
akrun

Reputation: 886938

The colSums works on a data.frame or matrix. When we subset the data into a vector (df1[,3]), it loses the dimensions. In case, we need to do colSums(df1[3]) or colSums(df1[,3, drop = FALSE]). But, for a single column as a vector, sum is only needed

rbind(df1, list(origin = "GrandTotal", destination_city2 = "", 
                    till_5 = sum(df1$till_5)))
#       origin destination_city2 till_5
#1          A           Chennai     72
#2          B        Coimbatore      4
#3          C            Jaipur      1
#4          D             Ajmer      3
#5          E            Jaipur      4
#6          F        Kishangarh      1
#7 GrandTotal                       85

Also, in the OP's example, there seems to be 3 columns, so we need to rbind with the same number of elements

Upvotes: 3

Matt
Matt

Reputation: 994

You want sum(df1$till_5). It's only one value, so you probably don't want to assign it to a whole new row in the data frame.

Upvotes: 1

Related Questions