34

我正在对数据进行分组,然后对其进行汇总,但也想保留另一列。我不需要对该列的内容进行任何评估,因为它始终与 group_by 列相同。我可以将它添加到 group_by 语句中,但这似乎并不“正确”。我想State.Full.Name在分组后保留State。谢谢

TDAAtest <- data.frame(State=sample(state.abb,1000,replace=TRUE))
TDAAtest$State.Full.Name <- state.name[match(TDAAtest$State,state.abb)]


TDAA.states <- TDAAtest %>%
  filter(!is.na(State)) %>%
  group_by(State) %>%
  summarize(n=n()) %>%
  ungroup() %>%
  arrange(State)
4

3 回答 3

35

也许我们需要

TDAAtest %>% 
     filter(!is.na(State)) %>%
     group_by(State) %>% 
     summarise(State.Full.Name = first(State.Full.Name), n = n())

或用于mutate创建列,然后执行distinct

TDAAtest %>% f
     filter(!is.na(State)) %>%
     group_by(State) %>% 
     mutate(n= n()) %>% 
     distinct(State, .keep_all=TRUE)
于 2016-08-23T04:05:27.790 回答
2

我相信有比接受的答案更准确的答案,特别是当您没有每个组中其他列的唯一数据时(例如,基于一个特定列的最大或最小或前 n 个项目)。

例如,尽管接受的答案适用于这个问题,但您希望找到每个州人口最多的县。(你需要有countypopulation列)。

我们有以下选择:

1.dplyr版本

这个链接,你有三个额外的操作(mutateungroupfilter来实现:

TDAAtest %>% 
     filter(!is.na(State)) %>%
     group_by(State) %>% 
     mutate(maxPopulation = max(Population)) %>% 
     ungroup() %>%
     filter(maxPopulation == Population)

2.功能版本

这为您提供了尽可能多的灵活性,您可以对每个组应用任何类型的操作:

maxFUN = function(x) {
  # order population in a descending order
  x = x[with(x, order(-Population)), ]
  x[1, ]
}

TDAAtest %>% 
     filter(!is.na(State)) %>%
     group_by(State) %>%
     do(maxFUN(.)) 

强烈建议将此用于更复杂的操作。例如,您可以返回topN每个州的前 n ( ) 个县,x[1:topN]方法是将返回的数据框放入maxFUN.

于 2021-06-23T05:42:01.523 回答
1

要保留所有列,您可以包含across()作为summarize参数,如dplyr::do().

by_cyl <- head(mtcars) %>%
  group_by(cyl)
by_cyl %>%
  summarise(m_mpg = mean(mpg), across())

    cyl m_mpg   mpg  disp    hp  drat    wt  qsec    vs    am  gear  carb
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     4  22.8  22.8   108    93  3.85  2.32  18.6     1     1     4     1
2     6  20.4  21     160   110  3.9   2.62  16.5     0     1     4     4
3     6  20.4  21     160   110  3.9   2.88  17.0     0     1     4     4
4     6  20.4  21.4   258   110  3.08  3.22  19.4     1     0     3     1
5     6  20.4  18.1   225   105  2.76  3.46  20.2     1     0     3     1
6     8  18.7  18.7   360   175  3.15  3.44  17.0     0     0     3     2

要仅保留未更改列的子集,您可以在across使用tidyselect语义中选择它们。

于 2022-01-01T08:34:43.237 回答