0

I store many objects (e.g. htest or lm) in a list. I would like to access the attributes (like p-values) of each object stored in this list.

I can access one attribute using l[[1]]$p.value. Is there a solution and access all attributes of one kind and store them in a vector using sapply or something similar?

data <- data.frame(x1 = runif(n = 100),
                   x2 = runif(n = 100),
                   x3 = sample(x = c(0,1), size = 100, replace = T))  

l <- list()

for(i in 1:2){
    l[[i]] <- t.test(data[,i] ~ data[,3])
}    

l[[1]]$p.value
jnshsrs
  • 337
  • 4
  • 11
  • 2
    You can check the `str(l)` and get the attributes that you need. From the list, `sapply(l, function(x) x$p.value)` gets the p.value – akrun Jun 01 '15 at 14:40
  • 1
    Use lapply with the function "[" followed by a number, the number is the that of the attribute. For example, lapply(l,"[",3) gives each of the p values. You can also use sapply. Hope I've understood your question. – DarrenRhodes Jun 01 '15 at 15:11
  • 3
    For the record, most components of the `t.test` return are not *attributes* in the *R*-sense. Components of the results are named, e.g., statistic, parameter, p.value, etc, and they are merely list elements. Some of those list elements have attributes themselves (e.g., the names of named vectors), which you would access via something like `attributes(l[[1]]$statistic)`. @user1945827's comment can also be done with `sapply` and/or using `[[` if you want to neck the response down to simpler vectors. – r2evans Jun 01 '15 at 15:46

0 Answers0