【问题标题】:Mean by group with losing any columns按组平均丢失任何列
【发布时间】: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


【解决方案1】:

@akrun:这行得通吗:

df %>% 
  group_by(Coordinates) %>% 
  summarise(State=Coordinates, Type=Type, across(where(is.numeric), ~mean(.x, na.rm = TRUE))) %>% 
  filter(row_number() %% 2 == 0) ## Select even rows

输出:

# Groups:   Coordinates [1]
  Coordinates State Type  `2002` `2003` `2004` `2005` `2006` `2007` `2008` `2009` `2010`
  <chr>       <chr> <chr>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 West        West  Debt    140.     55     83   830.     39   52.5     55   55.5     62

【讨论】:

  • 你也可以使用df %&gt;% mutate(State = Coordinates) %&gt;% group_by(State, Coordinates) %&gt;%..。我不确定 OP 在“坐标和状态”中的值如何。根据输入显示它似乎工作
【解决方案2】:

一种选择是首先将“状态”更改为“坐标”,然后应用公式方法,包括分组变量“状态”、“坐标”和“类型”

df$State <- df$`Location Coordinates`
aggregate(.~ State + `Location Coordinates` + Type,
            df, FUN = mean)

【讨论】:

  • 所以我才意识到列标题显示的是位置坐标而不是坐标。因此考虑到这一点,transform 将列名合并到 Location.Coordinates。但即使我进行了聚合(.~ State + Location.Coordinates + Type, transform(df, State = 'Location Coordinates'), FUN = mean) 我得到了全面的 NA 并将年份重命名为 X2002 , X2003 .. ...
  • @justcheckingsources 你需要匹配列名。如果列名中有空格,请将其反引号插入.
  • 我做了,但它说它不存在。这就是我写的:aggregate(.~ State + ‘Location Coordinates’+ Type, transform(df, State = ‘Location Coordinates’), FUN = mean) (用反引号替换‘)
  • @justcheckingsources 在我的帖子中尝试更新的解决方案。我假设列名是“位置坐标”
  • @justcheckingsources 有可能通过读取数据将带有空格的列名替换为Location.Coordinates,因为check.names = TRUE 默认情况下在read.csv/data.frame 构造中。在这种情况下,您在变换和聚合中都需要“Location.Coordinates”
猜你喜欢
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
  • 2012-12-18
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
相关资源
最近更新 更多