Combine t.test and var.test into a function in R -
Combine t.test and var.test into a function in R -
i trying combine f-test , t-test function r kept returning error.
ds <- structure(list(gender = structure(c(2l, 2l, 2l, 2l, 2l, 2l, 1l, 1l, 1l, 1l, 1l, 1l), .label = c("f", "m"), class = "factor"), ratings = c(4l, 1l, 3l, 4l, 5l, 5l, 5l, 3l, 1l, 5l, 4l, 5l )), .names = c("gender", "ratings"), class = "data.frame", row.names = c(na, -12l)) from basic statistics, if var.test returns value > 0.05, t.test should have parameter var.equal = true.
thus
> var.test(ds$ratings~ ds$gender) f test compare 2 variances data: ds$ratings ds$gender f = 1.1324, num df = 5, denom df = 5, p-value = 0.8948 alternative hypothesis: true ratio of variances not equal 1 95 percent confidence interval: 0.1584512 8.0922265 sample estimates: ratio of variances 1.132353 and t.test should be
> t.test(ds$ratings~ ds$gender, var.equal = true) 2 sample t-test data: ds$ratings ds$gender t = 0.1857, df = 10, p-value = 0.8564 alternative hypothesis: true difference in means not equal 0 95 percent confidence interval: -1.833149 2.166482 sample estimates: mean in grouping f mean in grouping m 3.833333 3.666667 i trying combine these 2 function such if p-value var.test < 0.05 should set var.equal = false , vice versa. r however, kept returning error.
super.t <- function(y,x) { tmp <- var.test(y~x) if tmp$p.value < 0.05 { tmp1 <- t.test(y~x, var.equal = false) } else { tmp1 <- t.test(y~x, var.equal = true) } return(tmp1) } super.t(ds$ratings~ ds$gender) thank ladies , gentlemen.
the reason code didn't work have set parentheses around tested if condition, like:
if (tmp$p.value < 0.05) { you calling function in wrong way, needed do:
super.t(ds$ratings,ds$gender) by making utilize of formula interface, data= argument, , fact var.equal= takes logical value, simplify things fair bit:
super.t <- function(form,data,level=0.05) { vareq <- var.test(form, data)[["p.value"]] >= level t.test(form, data, var.equal = vareq) } and phone call like:
super.t(ratings ~ gender, ds) r function
Comments
Post a Comment