I am trying to write a function which accepts Var1
and Var2
from user and run the t.test
and return the mean for female classification. But I am getting an error for the calc line. If I run the program without the paste and as.formula
functions and run with t.test(dat[[Var2]]~dat[[Var1]]
I will get the correct answer.
But in my original code I am required to use the paste function. Could anyone let me know what is the mistake in the code below using paste and as.formula functions? I am using the quine dataframe from MASS library.
func = function(dat=quine,Var1,Var2){
# calc = t.test(dat[[Var2]]~dat[[Var1]] #gives the answer
calc = t.test(as.formula(paste(dat[[Var2]], dat[[Var1]], sep="~"))) #gives an error
return(F.mean = calc$estimate[1])
}
func(Var1= "Sex", Var2= "Days")
Here is the head(quine)
Eth Sex Age Lrn Days
1 A M F0 SL 2
2 A M F0 SL 11
3 A M F0 SL 14
4 A M F0 AL 5
5 A M F0 AL 5
6 A M F0 AL 13