R从数据框中选择所有行,在该数据框中,一个值重复一列,但在另一列中具有特定值 [英] R select all rows from a dataframe where a value is duplicated one column but has a specific value in another column

查看:305
本文介绍了R从数据框中选择所有行,在该数据框中,一个值重复一列,但在另一列中具有特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从R数据框中提取一行中具有重复值但另一列中具有0或1的行.

I am trying to extract from my R dataframe, rows that have duplicate values in one column but which in another column have either a 0 or a 1.

例如,如果这是数据帧:

For example, if this is the dataframe:

Data <- data.frame(
+     X = c(1,3,5,7,7,8,9,10,10,11,11),
+     Y = sample(36476545:36476555),
+ timepoint = c(0,1,0,0,1,1,0,1,0,1,1)
+ )

看起来像

> Data
    X        Y timepoint
1   1 36476549         0
2   3 36476545         1
3   5 36476552         0
4   7 36476547         0
5   7 36476546         1
6   8 36476548         1
7   9 36476551         0
8  10 36476555         1
9  10 36476553         0
10 11 36476554         1
11 11 36476550         1

我想要的输出将是所有值重复在X中重复的行,其中一次出现该值的时间点= 0,另一次出现的时间点= 1,结果

My desired output will be all rows for which values are duplicated in X with timepoint = 0 for one occurrence of the value and 1 for the other occurrence, resulting in

> Data
    X        Y timepoint
4   7 36476547         0
5   7 36476546         1
8  10 36476555         1
9  10 36476553         0

请注意,由于在两种情况下时间点变量均为1,因此也不会计算在X中重复的最后两项数据. 有一个

Note that the last two items of data, which are also duplicated in X are not counted because the timepoint variable is 1 in both cases. There is a solution in SQL which comes close but I do not know how to code that in R.

解决方案,我首先尝试创建重复项的数据框,然后尝试从那里获取我想要的数据框:

Solution I tried by first creating a dataframe of the duplicates and then attempting to get the ones I want from there:

dupes <- Data[Data$X %in% 
Data$X[duplicated(Data$X)],]
ids <- Data$X[Data$timepoint==0]
Data[Data$X %in% ids,]

但是这将返回没有重复条目的行.任何帮助,将不胜感激,谢谢!

But this returned rows which do not have a duplicate entry. Any help would be appreciated, thank you!

推荐答案

是您要找的东西吗?

library(dplyr)

Data <- data.frame(
     X = c(1,3,5,7,7,8,9,10,10,11,11),
     Y = sample(36476545:36476555),
 timepoint = c(0,1,0,0,1,1,0,1,0,1,1)
 )

Data %>% 
  group_by(X) %>% 
  filter(dplyr::n_distinct(timepoint) == 2)

n_distinct返回向量中不同元素的数量.由于使用group by语句,因此仅返回每个组(X)具有两个不同时间点的行.

n_distinct returns the number of distinct elements in a vector. Due to the group by statement, only rows with two distinct timepoints per group (X) are returned.

dplyr::n_distinct(c(1, 2, 1, 3, 1))

Data %>% 
  group_by(X) %>% 
  mutate(n_distinct = dplyr::n_distinct(timepoint))

这篇关于R从数据框中选择所有行,在该数据框中,一个值重复一列,但在另一列中具有特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆