Camus
Camus

Reputation: 5

For loop only filling last element of a list - R

I am trying to do a Montecarlo process. For which, I am trying to do a massive resampling function.

For some reason, while doing a for loop, only the last element of the list is being filled with the small resample. What I need is a list in which each element of the list is a complete data.frame

I am doing this in R.

Thanks in advance!

#Montecarlo para obtener una distribución de diferentes estimaciones de Beta (Estimador de una población)

library(ggplot2) #data diamonds

#Población (Asumir como deconocida)
PopulationSize<-nrow(diamonds) 

#Ejemplo con una primera muestra de 100 observaciones
sample1 <- diamonds[ceiling(runif(100,1,PopulationSize)),]
print(sample1)

#Creando una función para realizar el remuestreo
Remuestrear <- function(cantidadMuestras, tamanoRemuestra, data){
  for(i in 1:cantidadMuestras){
    nSamples <- list()
      nSamples[[i]] <- data[ceiling(runif(tamanoRemuestra,1,nrow(data))),]
    print(nSamples[[i]])
  }
  return(nSamples)
}

Remuestras <- Remuestrear(10,100, diamonds)
Remuestras

Upvotes: 0

Views: 604

Answers (1)

rg255
rg255

Reputation: 4169

You are over-writing your list on each iteration of your loop. Move the nSamples <- list() to before the for(i in ....

Upvotes: 1

Related Questions