Home > database >  convert list to vector when use for loop in R
convert list to vector when use for loop in R

Time:04-19

How can I convert list to vector in R here?

a1 <- matrix(rcauchy(10*200, 0, 1), 200)

for (i in 1:150) {
  if (shapiro.test(a1[i,])$p.value >= 0.05) {
    print(t.test(a1[i,], alternative = "two.sided")$p.value)
  }
}

I use this code but I get only the first value

p <- NULL
for (i in 1:150) {
  p[i] <- if (shapiro.test(a1[i,])$p.value>=0.05) {
    (t.test(a1[i,], alternative = "two.sided")$p.value)
  }
}
p

CodePudding user response:

To make the code run without errors, you just need to have an else statement for when the condition is false

p <- NULL
for (i in 1:150) {
  p[i] <- if (shapiro.test(a1[i, ])$p.value >= 0.05) {
    (t.test(a1[i, ], alternative = "two.sided")$p.value)
  } else {
    NA
  }
  print(i)
}
p

CodePudding user response:

A apply loop solution.

a1 <- matrix(rcauchy(10*200, 0, 1), 200)

p <- apply(a1, 1, \(a){
  if(shapiro.test(a)$p.value >= 0.05)
    t.test(a)$p.value
  else NA_real_
})

Created on 2022-04-18 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related