我有一个从此获得的df(例如)
ID <- c("A","A","A","A","A","B","B","B","B","B")
Point_A <- c(10,25,30,40,50,60,75,80,90,100)
Point_B <- c(21,32,43,54,65,11,22,53,94,15)
df1 <- data.frame(ID,Point_A,Point_B)
我希望通过取值&lt;来对数据帧进行子集化。阈值(此处阈值= Point_A列的组中位数 - 7.5)。
我目前通过取整列的中位数并减去7.5来进行子设定。
df2 <- subset(df1, df1$Point_A < median(Point_A) - 7.5)
但是,我想取组中位数(每个ID的中位数。这里是A,B)然后减去7.5并进行子集化。
期望输出
ID Point_A Point_B
A 10 21
B 60 11
对于ID A,30是中位数,30 -7.5 = 22.5,因此A的输出中只出现10个。同样适用于B.
请指导我如何做到这一点。
答案 0 :(得分:2)
尝试
library(dplyr)
df1 %>% group_by(ID) %>% filter(Point_A < median(Point_A) - 7.5,
Point_B < median(Point_B) - 7.5)
或者,根据评论中的@Frank建议:
mycond <- function(x) x < median(x) - 7.5
df1 %>% group_by(ID) %>% filter(mycond(Point_A), mycond(Point_B))
给出了:
#Source: local data frame [2 x 3]
#Groups: ID
#
# ID Point_A Point_B
#1 A 10 21
#2 B 60 11
修改强>
我可能误解了你的初步问题。如果您只想过滤Point_A
,请执行以下操作:
df %>% group_by(ID) %>% filter(Point_A < median(Point_A) - 7.5)