How to use Aggregate function in R

2019-01-23 20:09发布

can you help me please how to properly use aggregate function in R? I have data like this:

SPORT   FLOWS
[1,] "Other" "1"  
[2,] "Other" "1"  
[3,] "Other" "1"  
[4,] "Other" "1"  
[5,] "Other2" "1"  
[6,] "Other2" "1"

And I need to get this:

SPORT   FLOWS
[1,] "Other" "4"
[2,] "Other2" "2"

I found, that it can be done with aggregate function, but it doesn't work..

Thank you guys.. I have marked answer which worked for me..

标签: r aggregation
2条回答
我命由我不由天
2楼-- · 2019-01-23 20:32
aggregate(FLOWS ~ SPORT, dat, function(x) sum(as.numeric(x)))

where dat is the name of your matrix.

Here, the function is.numeric is necessary to transform the second column into numbers.

查看更多
相关推荐>>
3楼-- · 2019-01-23 20:47

Assuming your dataframe is named "sport_data", I think you just want:

aggregate(sport_data, sport_data$SPORT, sum)

If you just have individual counts (that are all equal to 1), then "tabulate" may be a simpler option.

Please let us know what kind of errors you are getting. (if this doesn't work, or in the future, in your question)

查看更多
登录 后发表回答