Referencing a List of Variables in Do Loop

80 views Asked by At

I have created a series of multimodal distributions to test the effectiveness of the Hartigan dip test for unimodality. These distributions each have 2000 observations and created using one or more rnorm function.

The purpose of this code is outlined below.

  1. Calculate the dip statistic for each distribution to be stored in the "statistic" variable

  2. Extract the p-value into the "dipstatistic" variable and store them for later use

  3. Reference this variable after every distribution has undergone this calculation to be assessed at a later date

I believe that the problem I have here is in indicating the variables that are generated outside of the loop. Does anyone have any advice of how to rectify this probelm?

x1 <- rnorm(2000,4,.5)

x2 <- c(rnorm(1000,0,1),rnorm(1000,4,1)) 

x3 <- c(rnorm(667,0,1),rnorm(667,4,1),rnorm(666,8,1))

x4 <- c(rnorm(500,0,1),rnorm(500,4,1),rnorm(500,8,1),rnorm(500,12,1))

dip.test(x1, simulate.p.value = FALSE, B = 2000)
dip.test(x2, simulate.p.value = FALSE, B = 2000)
dip.test(x3, simulate.p.value = FALSE, B = 2000)
dip.test(x4, simulate.p.value = FALSE, B = 2000)

y=4

dipstatistic <- rep(0,y)

ID <- 1:y
for (i in 1:y) {
  statistic <- dip.test("need to find way to identify variables" , simulate.p.value = FALSE, B = 2000)
  dipstatistic[i] <- statistic$p.value
}

dipstatistic
1

There are 1 answers

3
MrFlick On BEST ANSWER

You could just use an sapply here if you join all your variables in a list.

dipstatistic <- sapply(list(x1,x2,x3,x4), function(x) {
    dip.test(x , simulate.p.value = FALSE, B = 2000)$p.value
})