gpt4 book ai didi

r - 如何将重复值分组为单个值并在 R 中提取与该列值关联的值?

转载 作者:行者123 更新时间:2023-12-04 09:49:24 24 4
gpt4 key购买 nike

我有一个看起来像这样的数据框:


df <- data.frame(
Location = c("buildinga", "buildinga", "buildinga", "buildingb", "buildingb", "buildingb", "buildingc", "buildingc", "buildingc),
Category = c(candy, candy, snacks, candy, snacks, soda, soda, candy, soda)
Calories = 200, 250, 150, 180, 200, 80, 140, 200, 210)
)

我想按单个建筑物对“位置”进行分组,并为每个位置提取相应的值(因此建筑物 a、b 和 c 具有糖果、零食和苏打水的总卡路里)。

我尝试执行 group_by(location) %>% summarize(count(n=()) 但这仍然给了我每个位置。我想删除重复的位置但不是'类别'或'卡路里'。

最佳答案

使用 dplyr,您可以group_by 您的数据并计算每个类别中的卡路里。

library(dplyr)
df %>%
group_by(Location, Category) %>%
summarise(Count = sum(Calories))

# A tibble: 7 x 3
# Groups: Location [3]
Location Category Count
<fct> <fct> <dbl>
1 buildinga candy 450
2 buildinga snacks 150
3 buildingb candy 180
4 buildingb snacks 200
5 buildingb soda 80
6 buildingc candy 200
7 buildingc soda 350

是您要找的吗?

数据

您的数据示例有一些拼写错误,这是我使用的:

df <- data.frame(
Location = c("buildinga", "buildinga", "buildinga", "buildingb", "buildingb", "buildingb", "buildingc", "buildingc", "buildingc"),
Category = c("candy", "candy", "snacks", "candy", "snacks", "soda", "soda", "candy", "soda"),
Calories = c(200, 250, 150, 180, 200, 80, 140, 200, 210)
)

关于r - 如何将重复值分组为单个值并在 R 中提取与该列值关联的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58963331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com