r - How to group duplicate values to a single value and pull associated values with that column value in R?
问题描述
I have a dataframe that looks like so:
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)
)
I want to group 'Location' by just a single building and pull corresponding values for each location (so building a, b and c have total calories for candy, snacks, and soda).
I tried doing group_by(location) %>% summarize(count(n=()) but that still gave me each location. I want to remove duplicates for location but not for 'Category' or 'Calories'.
解决方案
Using dplyr
, you can group_by
your data and count calories in each category.
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
Is it what you are looking for ?
Data
Your data examples has some typo issues, here is the one that I used:
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)
)
推荐阅读
- javascript - 为什么我的代码特定部分的代码“backpack.unshift("Rock")" 在我的背包数组中没有 unshift()"Rock"?
- excel - Excel VBA - 创建记录表
- c++ - 仅当它不是别名时,如何编写 std::chrono::high_resolution 时钟类模板专业化
- php - 需要模态在另一个项目文件夹 Bootsrap 4 中不起作用
- google-analytics - GTM 仅在调试模式下触发我的标签。在实时模式下,它仅适用于 Chrome
- java - Spring boot 2 使用 AWS API Gateway 激活 spring 配置文件
- android - Android 上的 Web 推送通知
- swiftui - 从 datepicker 获取和设置日期,但仍然获得旧的默认值
- reactjs - 命令 C 不会阻止本地服务器在 VS 代码上运行
- c# - 如何在 Syncfusion Blazor 中以全宽和自动高度显示整个世界地图?