首页 > 解决方案 > 从数据框中子集整个集群

问题描述

在下面的 data.frame 中,我想知道如何对一个比其中更大的整个集群进行子studyoutcome1

我想要的输出如下所示。我试过subset(h, outcome > 1)了,但这并没有给出我想要的输出。

h = "
study outcome
a     1
a     2
a     1
b     1
b     1 
c     3
c     3"
h = read.table(text = h,h=T)

DESIRED OUTPUT:
"
study outcome
a     1
a     2
a     1
c     3
c     3"

标签: rdataframesubset

解决方案


修改subset-

  1. 基于第一个逻辑表达式的“研究”子集outcome > 1
  2. %in%在“研究”上使用以创建最终的逻辑表达式subset
subset(h, study %in% study[outcome > 1])

-输出

 study outcome
1     a       1
2     a       2
3     a       1
6     c       3
7     c       3

如果我们想限制'结果'值为1的'study'元素的数量,即第一个'n''study',然后unique从子集的第一个表达式中获取'study',head用于获取第一个'n' “研究”值并用于%in%创建逻辑表达式

n <- 3
subset(h, study %in% head(unique(study[outcome > 1]), n))

或者可以通过一组方法来完成any

library(dplyr)
h %>%
    group_by(study) %>%
    filter(any(outcome > 1)) %>%
    ungroup

推荐阅读