【发布时间】:2021-07-01 13:47:55
【问题描述】:
我需要在不丢失任何列的情况下计算下面示例表的每组(即每个坐标)的平均值(实际表有超过 40,000 行具有不同的状态、位置坐标和类型)所以这个:
| State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| California | West | Debt | 234 | 56 | 79 | 890 | 24 | 29 | 20 | 24 | 26 |
| Nevada | West | Debt | 45 | 54 | 87 | 769 | 54 | 76 | 90 | 87 | 98 |
会变成这样:
| State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| West | West | Debt | 234 | 56 | 79 | 890 | 24 | 29 | 20 | 24 | 26 |
当我使用聚合时 (df
| Location Coordinates | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 | |||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| West | 235 | 55 | 83 | 843 | 24 | 29 | 20 | 24 | 26 | Debt | 54 | 769 | 76 | 87 |
当我使用 sqldf 时,它会平均年份并变成这样:
| State | Location Coordinates | Type | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| West | West | Debt | 2002 | 2003 | 2004 | 2005 | 2006 | 2007 | 2008 | 2009 | 2010 |
有什么建议吗?
【问题讨论】:
-
你可以试试
aggregate(.~ State + Coordinates + Type, df, mean)
标签: r dataframe aggregate sqldf spread