'Creating a function that inputs data and outputs results in a list
I am looking to create a function that take in data, perform a test, and then release the data to a list. The primary issue I'm having is how to get the list output to call from the previous if_else statement and say which type of test it is, and the summary of the tests. I'm pretty new to OOP, especially in R, so a little lost but here is what I have so far.
## Function
con_function <- function(x, y, alpha = 0.05) {
if (var(x) == var(y)) {
print(t.test(x, y, var.equal = TRUE))
} else if (var(x) != var(y)) {
print(t.test(x, y, var.equal = FALSE))
}
output_list <- list(data1 = x, data2 = y, # test_type = ?, reject_null = ?,
attr(output, "class") <- "example"
}
Solution 1:[1]
Your function can be simplified a bit. You can store the t test object and pull elements out of it with the $ operator
set.seed(47); x=rnorm(40,mean=18,sd=17)
set.seed(50); y=rnorm(40,mean=16,sd=17)
## Constructor Function
con_function <- function(x, y, alpha = 0.05) {
tt <- t.test(x, y, var.equal = (var(x) == var(y)))
structure(list(data1 = x, data2 = y, test = tt$method,
reject_null = tt$p.value < alpha),
class = "example")
}
con_function(x, y)
#> $data1
#> [1] 51.909838 30.089423 21.151890 13.209995 19.849184 -0.457537
#> [7] 1.246803 18.257225 13.715220 -6.917755 2.318244 18.673241
#> [13] 26.394943 -13.079896 19.555040 29.403247 16.621673 39.492099
#> [19] 6.042401 17.310171 -8.624755 22.235519 12.212928 25.092244
#> [25] 12.450065 2.865002 -9.338719 -21.480329 -15.442726 18.467956
#> [31] 26.221270 20.453740 -2.407491 33.048921 33.077896 18.011668
#> [37] 6.214965 22.434220 26.613678 27.593131
#>
#> $data2
#> [1] 25.344388 1.692736 16.560965 24.910545 -13.369270 11.276303
#> [7] 22.134084 5.954488 32.585039 -8.577749 21.018515 25.430788
#> [13] 7.523196 19.327475 8.255811 9.831457 13.334172 2.990726
#> [19] -3.822295 10.501763 10.051235 6.022749 -11.027920 44.722512
#> [25] 25.580922 61.349768 22.061094 9.843953 25.668688 16.487467
#> [31] 19.383398 1.525821 -3.217641 26.153232 -2.632814 16.324641
#> [37] 23.075383 47.274487 22.905172 22.684770
#>
#> $test
#> [1] "Welch Two Sample t-test"
#>
#> $reject_null
#> [1] FALSE
#>
#> attr(,"class")
#> [1] "example"
Created on 2022-04-09 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |
