如何删除给定ID只有1种组合的行 [英] How to remove rows that have only 1 combination for a given ID
本文介绍了如何删除给定ID只有1种组合的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的数据帧
I have a dataframe like this
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种组合的行。
I want to remove rows that have only 1 combination for a given ID.
我这样做是为了删除只有1列和1个唯一值的数据框中的行。
I do something like this to remove rows in a dataframe that has only 1 column with 1 unique value.
df_count <- length(unique(df$Measurement))
if(df_count < 2)
next
我正在尝试将其扩展为在具有2的组合的数据框中使用专栏,我无法使用相同的逻辑。请提供一些有关如何解决此问题的帮助
I am trying to extend that to use in a data frame that has a combination of 2 columns and I am not able to use the same logic. Please help with some inputs on how to solve this
推荐答案
在dplyr中,应该是
In dplyr, it would be
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
这篇关于如何删除给定ID只有1种组合的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文