I have the following data frame
patientID<-c(1,2,3,4,5,6,7,8)
age<-c(25,30,28,52,45,26,36,32)
s<-c("m","w","w","m","w","w","m","w")
diabetes<-c("T1","T2","T2","T3","T1","T2","T1","T1")
status<-c("poor","ïmproved","poor","ïmproved","Excellent","poor","ïmproved","Excellent")
patientenData<-data.frame(patientID,age,diabetes,status,s)
and want to write a filter as follows
filter<-c(s=="m","age>28","OR",s=="w","age>38")
filter<-paste(filter,collapse="&")
filter<-gsub("&OR&","|",filter)
patientenData<-patientenData[with(patientenData,eval(parse(text=filter))),]
The problem is, to be able to execute the last part I need an "string of an string". I mean
filter<-c("s=="m"","age>28","OR","s=="w"","age>38")
because of parse
and eval
. But it is not easily possible. I tried toString
and is.character
or as.character
too but without success. Thanks for every hint.
data.table package is a much better way to go:
library(data.table)
patientID<-c(1,2,3,4,5,6,7,8)
age<-c(25,30,28,52,45,26,36,32)
s<-c("m","w","w","m","w","w","m","w")
diabetes<-c("T1","T2","T2","T3","T1","T2","T1","T1")
status<-c("poor","ïmproved","poor","ïmproved","Excellent","poor","ïmproved","Excellent")
patientenData<-data.table(patientID,age,diabetes,status,s)
As a data.table you can then write a SQL like query
filtered<-patientenData[s=='m' & age>28 | s =='w'&age>38]
with subset()
from {base}
:
filtered <- subset(patientenData, s=='m' & age>28 | s =='w' & age>38)
with indexing:
filtered <- patientenData[with(patientenData, s=='m' & age>28 | s =='w' & age>38), ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.