我在 R 中有以下数据框(对于熟悉 tidyverse 的人来说,它是 starwars 示例数据集)
我正在尝试创建一个输出两列的 tibble:homeworld
和 shortest_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 确实列出了 homeworld
和 shortest_5
,但它重复了同一个 homeworld
的多个实例。
似乎是一个简单的修复,但我无法完全理解它!任何帮助将不胜感激!
答案 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.
注意:
答案 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