How to use Aggregate function in R

血红的双手。 提交于 2019-11-27 16:56:02

问题


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..


回答1:


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.




回答2:


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)



来源:https://stackoverflow.com/questions/20620764/how-to-use-aggregate-function-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!