How to sum columns to create a new row of data in a dataframe

Hi all,
I have a dataframe that looks like this:

test
a b c d e f g
1 27 56 87 32 0 5 6
2 0 0 20 21 12 5 6

I would like to sum the column data to create a new row, like this:

test1
a b c d e f g
1 27 56 87 32 0 5 6
2 0 0 20 21 12 5 6
12 27 56 107 53 12 10 12

This seems like it should be really easy to do, but can't seem to figure it out. That or I am using the wrong search syntax to do a search for this topic. Any help greatly appreciated.

Cheers,
bugstatsguy

maybe see this question from stack overflow?

Assuming your data is *dat1

dat1[nrow(dat1) + 1, ]  <-  colSums(dat1)

This assumes all columns are numeric.

You may try jannitor::adorn_totals("rows")

I think the expected result of adding 1 and 2 in your example first columns is wrong, or at least doesn't correspond to the other summations which use addition

I am not sure but that first "column" looks like rom.names to me. There appears to be 6 cor.names and 7 columns.

Hmm, perhaps your right, but then is that to be a 12th row? Anyway, probably irrelevant to the question/issue :sweat_smile:

Could be or some typo? It makes no sense in any case. The rest of the columns in the example sum correctly.

Hi all,
just a clarification, the first column was just a rowname: "1", and "2", with a rowname "12" in the summed dataframe. Sorry for the confusion.
Both the solutions proposed by jrkrideau and ainsuasty seemed to work.
Thank you for the advice

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.