本文介绍了R-dplyr汇总并保留其他列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am grouping data and then summarizing it, but would also like to retain another column. I do not need to do any evaluations of that column's content as it will always be the same as the group_by column. I can add it to the group_by statement but that does not seem "right". I want to retain State.Full.Name after grouping by State. Thanks

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)


推荐答案

也许我们需要

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






或使用 mutate 创建列,然后执行与众不同

TDAAtest %>% f
     filter(!is.na(State)) %>%
     group_by(State) %>%
     mutate(n= n()) %>%
     distinct(State, .keep_all=TRUE)

这篇关于R-dplyr汇总并保留其他列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 03:27