-3

I have the following data.frame, these are terror events happened in countries and the there can be 200 rows just for one country:

Classes ‘data.table’ and 'data.frame':  80999 obs. of  3 variables:
 $ country_txt.factor: Factor w/ 166 levels "Afghanistan",..: 102 102 65 79 131 65 79 150 135 135 ...
 $ nkill             : num  0 0 1 0 6 0 0 0 0 0 ...
 $ nwound            : num  7 7 2 1 10 0 0 0 1 0 ...

I would like to create a new data.frame/table where i could make a summary like this:

Country    Number of kills(sum)   Number of wounds (sum)
Iraq       14000                  150000
Afghanistan 10000                 8888
.
.
.

Can you help me please how could i do this?

user3551399
  • 93
  • 2
  • 11

2 Answers2

2

You can use the aggregate function on two variables and use sum in the FUN argument.

summaryDf <- aggregate( data = df , cbind(nkill, nwound) ~ country_txt.factor, FUN = sum)
DataTx
  • 1,839
  • 3
  • 26
  • 49
1

We can group by 'country_txt.factor' and loop over the other columns to get the sum in data.table

library(data.table)
dt[, lapply(.SD, sum) , country_txt.factor]
akrun
  • 874,273
  • 37
  • 540
  • 662