maniA
maniA

Reputation: 1457

How can I have a string of string in R?

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.

Upvotes: 1

Views: 49

Answers (2)

jogo
jogo

Reputation: 12569

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), ]

Upvotes: 1

SamanthaDS
SamanthaDS

Reputation: 1143

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]

Upvotes: 3

Related Questions