filter id in cluster according another variable in R

折月煮酒 提交于 2019-12-20 06:45:43

问题


I have a data with 100 patients and each patient has values from 7 days (1 to 7). How can I select only patients according another variable only in day 1?

df <- data.frame(id = c(1, 1, 1, 2, 2, 2),
         day = c(1, 2, 3, 1, 2, 3),
         RRT = c(0, 1, 0, 1, 0, 0))

I want select only id whom had RRT=0 at day = 1.


回答1:


When using dplyr:

library(dplyr)
df %>% 
  group_by(id) %>% 
  filter(day == 1 & RRT == 0) %>% 
  select(id)

or base R:

df[df$day == 1 & df$RRT ==0,"id"]



回答2:


You can use the subset function in base R:

subset(df,RRT==0&day==1)

if you only need the id column the you can select

with(df,id[RRT==0&day==1])


来源:https://stackoverflow.com/questions/47977120/filter-id-in-cluster-according-another-variable-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!