![](/img/trans.png)
[英]Obtaining samples of pairs so that there is not repetition of any value in any of the combinations (R)
[英]Finding unique pairs in R (with no repetition of ANY values)
我有一个数据框,其中包含2组患者(x和y组)的血液检查结果。 每个队列中有相同数量的患者(具有不同的身份证号)(2000年)。 我对计时很感兴趣,在测试时他们(模糊)加入了。 由于测试时间上有很多比赛,这导致时间段相似的两组中的ID重复。
这是一个例子:
id.x time value id.y time value
1 23 4.1 11 18 4.3
1 23 4.1 12 25 4.8
2 54 3.9 13 51 4.3
2 54 3.9 14 52 4.0
3 72 4.5 14 70 4.3
3 72 4.5 15 25 4.3
x和y组中的id数比为1:1。
我正在尝试找到唯一的对,其中任一列均不重复ID。 我努力了
test.df %>% distinct(id.x, .keep_all = TRUE)
这一半有效-我从id.x获得唯一值,但是它们与重复的id.y值匹配,因为我没有指定这些值也必须是唯一的。
我也尝试过
testsample.df <- unique(test.df[,c('icustay_id.x', 'icustay_id.y')])
这导致唯一的对,即不重复每个对,但每个id以所有可能的组合重复多次。
我不确定这是否可能。
我最接近的是一个两阶段过程-使用随机唯一ID.y进行二次采样,然后使用以下代码使用唯一ID.x进行二次采样:
subsampled_data <- ddply(test.df,.(test.df$id.y), function(x)
{x[sample(nrow(x),size=1),]})
subsampled_data2.df <- ddply(subsampled_data,.(subsampled_data$icustay_id.x),
function(x) {x[sample(nrow(x),size=1),]})
这样做,我成功地获得了只有唯一ID的唯一对。 但是我损失了很多行,从2000年到〜1000。
是否有可能找到具有唯一ID的唯一对,而又不会在每个步骤中丢失那么多?
谢谢!
我不确定您的预期输出是多少。 但是希望这会有所帮助。
样本数据:
df <- data.frame(id.x = c(1,1,2,2,3,3), id.y = c(11,12,13,13,13,13))
id.x
唯一值:
df <- df[!duplicated(df$id.x), ]
id.x id.y
1 1 11
3 2 13
5 3 13
现在我们在id.y
仍然有重复id.y
并执行
df <- df[!duplicated(df$id.y), ]
删除它们。
这导致:
id.x id.y
1 1 11
3 2 13
或使用dplyr
:
df %>% distinct(id.x, .keep_all = TRUE) %>% distinct(id.y, .keep_all = TRUE)
收益:
id.x id.y
1 1 11
2 2 13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.