首页 > 解决方案 > 如何在R中将两行的值合并在一起

问题描述

我正在尝试将 2 行合并在一起,但似乎找不到方法。

我使用了 geom_col() 并且有两行尼日利亚行。一个标有“尼日利亚”,另一个标有“尼日利亚”。我想将这两行的“sum_gt”值合并为一行。

这是我的代码:

plastics %>% 
select(country, year, grand_total) %>%
filter(country != "EMPTY") %>% 
drop_na(grand_total) %>%
group_by(country) %>% 
summarize(sum_gt = sum(grand_total)) %>%
arrange(desc(sum_gt)) %>% 
ggplot(aes(reorder(x = country, sum_gt), y = sum_gt, fill = country)) +
geom_col() +
coord_flip() +
theme(legend.position = "none")

数据集来自 TidyTuesday,这里是 URL:

塑料 <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-01-26/plastics.csv')

标签: rtidyverse

解决方案


如果要对它们求和,它们必须具有相同的名称。您的数据集中还有“ECUADOR”和“Ecuador”。为确保您掌握所有情况,我建议您在开始管道之前执行以下操作:

plastics$country<- tolower(plastics$country)

推荐阅读