如何删除R中的重复行?

时间:2021-02-09 12:17:01

标签: r dplyr

我在 R 中有以下数据框(对于熟悉 tidyverse 的人来说,它是 starwars 示例数据集)enter image description here

我正在尝试创建一个输出两列的 tibble:homeworldshortest_5(来自该家乡的 5 个人的平均身高)。

下面是我的代码;

df<-starwars %>%
  group_by(homeworld) %>%
  filter(!is.na(height), !is.na(homeworld)) %>%
  arrange(desc(height)) %>%
  mutate(last5mean = mean(tail(height, 5))) %>%
  summarize(shortest_5=last5mean, number=n()) %>%
  filter(number>=5, ) 
df

看来我已经成功做到了(虽然它很乱)。我的问题是,虽然我的 tibble 确实列出了 homeworldshortest_5,但它重复了同一个 homeworld 的多个实例。

enter image description here

似乎是一个简单的修复,但我无法完全理解它!任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

您可以大大缩短代码:

df<-starwars %>%
  group_by(homeworld) %>%
  filter(!is.na(height), !is.na(homeworld), n() >=5) %>%
  summarize(shortest_5 = mean(if_else(rank(height) > 5, NA_integer_, height), na.rm = TRUE))

df

# # A tibble: 2 x 2
#   homeworld shortest_5
#   <chr>          <dbl>
# 1 Naboo           151.
# 2 Tatooine        153.

注意:

  • 我得到的结果与你不同,例如在 Naboo 上,最短的 5 个字符的高度为:96、157、165、165、170。这 5 个值的平均值为 150.6。
  • 你不应该有例如科洛桑,因为那个母星只有 3 个角色。仅有的两个至少 5 个字符的家园是 Naboo 和 Tatooine。

答案 1 :(得分:0)

您可以使用 library(tidyverse)duplicate() 函数删除重复数据

例如

library(tidyverse)
df <- c(1,1,2,3,4,4,5,6,10,10,10)

检查哪些数据是重复的

df[duplicated(df)] # notice it shows 1, 4, and 10

删除重复项

New_DF <- df[!duplicated(df)] # all duplicate data removed