gpt4 book ai didi

r - 如何删除给定 ID 只有 1 个组合的行

转载 作者:行者123 更新时间:2023-12-04 11:46:12 25 4
gpt4 key购买 nike

我有这样一个数据框

ID <- c("A","A","A","B","B","C","C")
Measurement <- c ("Length","Breadth","Breadth","Breadth","Length","Length","Length")
Value <- c(4.5,6.6,7.5,3.3,5.6,8.9,16.1)
df <- data.frame(ID,Measurement,Value)
df

ID Measurement Value
1 A Length 4.5
2 A Breadth 6.6
3 A Breadth 7.5
4 B Breadth 3.3
5 B Length 5.6
6 C Length 8.9
7 C Length 16.1

我想要的输出是

  ID Measurement Value
1 A Length 4.5
2 A Breadth 6.6
3 A Breadth 7.5
4 B Breadth 3.3
5 B Length 5.6

我想删除给定 ID 只有 1 个组合的行。

我这样做是为了删除数据框中只有 1 列和 1 个唯一值的行。

df_count <- length(unique(df$Measurement))
if(df_count < 2)
next

我正在尝试扩展它以在具有 2 列组合的数据框中使用,但我无法使用相同的逻辑。请提供一些有关如何解决此问题的意见

最佳答案

在 dplyr 中,它会是

library(dplyr)

df %>% group_by(ID) %>% filter(n_distinct(Measurement) > 1)
## ID Measurement Value
## <fctr> <fctr> <dbl>
## 1 A Length 4.5
## 2 A Breadth 6.6
## 3 A Breadth 7.5
## 4 B Breadth 3.3
## 5 B Length 5.6

关于r - 如何删除给定 ID 只有 1 个组合的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38232998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com