1

I have a data frame and I need to apply the bartlett.test() function for each column in it. If possible, I needed to run it with the apply() or sapply() functions.

My sample data is like:

df <- data.frame(ENSG00000000003 = c(10, 50, 30, 40), ENSG00000000419 = c(20, 60, 100, 24), ENSG00000000457 = c(1, 10, 20, 70), group = c("yes","no","no","yes"))
rownames(df) <- c("sample01", "sample02", "sample03", "sample04")
df
         ENSG00000000003 ENSG00000000419 ENSG00000000457 group
sample01              10              20               1   yes
sample02              50              60              10    no
sample03              30             100              20    no
sample04              40              24              70   yes

Running for an individual column, my code would be:

pvalue <- bartlett.test(ENSG00000000003 ~ group, df)

pvalue

    Bartlett test of homogeneity of variances

data:  ENSG00000000003 by group
Bartlett's K-squared = 0.10672, df = 1, p-value = 0.7439

My expected output would have the Bartlett's test p-value in the last row of my data frame.

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89

1 Answers1

0

Here is a way using lapply():

res <- lapply(df[,-4], bartlett.test, df$group)
ps  <- sapply(res, getElement, "p.value")
df  <- rbind(df, pval=c(ps, NA))
df
         ENSG00000000003 ENSG00000000419 ENSG00000000457 group
sample01      10.0000000      20.0000000       1.0000000   yes
sample02      50.0000000      60.0000000      10.0000000    no
sample03      30.0000000     100.0000000      20.0000000    no
sample04      40.0000000      24.0000000      70.0000000   yes
pval           0.7439055       0.1417199       0.1950732  <NA>

Here is another way using a package:

library(matrixTests)
ps <- col_bartlett(df[,-4], df$group)$pvalue
df <- rbind(df, pval=c(ps, NA))
df
         ENSG00000000003 ENSG00000000419 ENSG00000000457 group
sample01      10.0000000      20.0000000       1.0000000   yes
sample02      50.0000000      60.0000000      10.0000000    no
sample03      30.0000000     100.0000000      20.0000000    no
sample04      40.0000000      24.0000000      70.0000000   yes
pval           0.7439055       0.1417199       0.1950732  <NA>
Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89