【发布时间】:2021-04-08 15:49:02
【问题描述】:
我有一个包含位置列和县列的数据框,其中显示了一组县的不同位置的数据。我按县列分组以进行另一个计算,但我想保留一种方法来查看每个县中包含哪些位置。这可能吗?
以下是原始数据的示例:
location county x y
hend hender 2 10
alam alam 0 5
alex alam 4 3
alleg allegy 6 1
ann hender 9 0
这也是我改变的:
df <- df %>%
group_by(county) %>%
summarise(total = sum(x + y))
county total
hender 17
alam 12
allegy 7
同样,不确定这是否可行,但我希望第三列(我们称之为 allloc)显示每个县的位置,如果可能,用逗号分隔。像这样的:
county total allloc
hender 17 hend, ann
alam 12 alam, alex
allegy 7 alleg
我尝试使用汇总和粘贴、变异、粘贴和合并,但均未成功。
df <- df %>%
group_by(county) %>%
summarise(allloc = paste(location))
df <- df %>%
group_by(county) %>%
mutate(allloc = paste(location))
df <- df %>%
group_by(county) %>%
mutate(allloc = coalesce(df$location))
有什么想法吗?
(最后但同样重要的是,这里有一些可重现的代码):
df <- data.frame(location = c("hend", "alam", "alex", "alleg", "ann"), county = c("hender", "alam", "alam", "allegy", "hender"), x = c(2, 0 , 4, 6, 9), y = c(10, 5, 3, 1, 0))
【问题讨论】:
标签: r dataframe group-by grouping tidyverse