我在 R 中有以下数据框(对于任何熟悉 tidyverse 的人来说,这是星球大战样本数据集)
我正在尝试创建一个输出两列的小标题:
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
看来我已经成功地做到了(虽然很乱)。我的问题是,虽然我的小标题确实列出了
homeworld
和 shortest_5
,但它重复了相同 homeworld
的多个实例。
似乎是一个简单的修复,但我无法完全理解它!任何帮助将非常感激!
您可以使用
duplicate()
函数删除重复数据
例如
df <- c(1,1,2,3,4,4,5,6,10,10,10)
检查哪些数据是重复的
df[duplicated(df)] # notice it shows 1, 4, and 10 (Note: need to add a comma if your df has more than one column, such as here: New_DF <- df[!duplicated(df),]
删除重复项
New_DF <- df[!duplicated(df)] # all duplicate data removed
您可以大大缩短代码:
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.
注: