R Programming Calculation of a two-tier t-test for a formatted data frame.

Good evening, I have the following data frame:

Sex A  B  C D  E
M   1 20 45 42 12
F   2 10 32 23 43
M   39 32 2 23 43
M   24 43 2 44 12
F   11 3 4 4 11

How would I calculate a t-test with two samples for each numeric variable for the data frame listed above using the apply variable. The result should be a matrix containing five columns: F.mean (mean of the numeric variable for Female), M.mean (mean of the numeric variable for men), t (for t-statistics), df (for degrees of freedom) and p (for p -values).

Thank!

+4
source share
2 answers

Here is an option using applywith a field2

out = apply(data[,-1], 2, function(x){ 
            unlist(t.test(x[data$Sex == 'M'], x[data$Sex == 'F'])[c(1:3,5)],
            recursive=FALSE)
       })

#> out
#                            A           B           C          D          E
#statistic.t         1.2432059  3.35224633 -0.08318328  1.9649783 -0.2450115
#parameter.df        2.5766151  2.82875770  2.70763487  1.9931486  1.8474695
#p.value             0.3149294  0.04797862  0.93946696  0.1887914  0.8309453
#estimate.mean of x 21.3333333 31.66666667 16.33333333 36.3333333 22.3333333
#estimate.mean of y  6.5000000  6.50000000 18.00000000 13.5000000 27.0000000

<strong> data

data = structure(list(Sex = structure(c(2L, 1L, 2L, 2L, 1L), .Label = c("F", 
"M"), class = "factor"), A = c(1L, 2L, 39L, 24L, 11L), B = c(20L, 
10L, 32L, 43L, 3L), C = c(45L, 32L, 2L, 2L, 4L), D = c(42L, 23L, 
23L, 44L, 4L), E = c(12L, 43L, 43L, 12L, 11L)), .Names = c("Sex", 
"A", "B", "C", "D", "E"), class = "data.frame", row.names = c(NA, 
-5L))
+3
source

apply, t.test aggregate, . . , t.test

+1

All Articles