Here is my dataset
mydata<-data.frame(
id=1:20,
sex=sample(c(rep("M",6),rep("F",14))),
Age=round(rnorm(20, 30,2)),
Weight=round(rnorm(20, 65,5),2)
)
I want my function to allow me to specify on which variable I want to do the filtering but also the criterion, i.e. the operator (== or > or <=...)
and the value (M or 65...)
This is the function I am trying to create. I know in advance that it won't work, it's to give an idea of what I want to create.
If I don't put the variable, value and operator of selection my function must return the original database otherwise the filtered database
my_func<-function(select_var, select_crit){
mydata<-mydata<-if(is.null(select_var)&is.null(select_crit)){mydata}else{
mydata[ which(mydata[select_var]select_crit), ]
}
return(mydata)
}
For example I want to be able to select all the male with my function like this
my_func(select_var="sex",select_crit="M"),
And all the induvidual > 30 (in age) like this:
my_func(select_var="Age",select_crit=">30")
or to select with the operator %in%
my_func(select_var="Age",select_crit=%in%c(30:40))