How to edit the loop to save the mean of each sample to a matrix in R?

set.seed(89235)
values<-c(10, 5, 10, 25, 50, 100, 500, 1000)
n=length(values)
for (i in 1:n){
mymean<- mean(rnorm(values[i], mean=0, sd=1))  
cat("sample size:",values[i],"mean:", mymean, fill=TRUE)
}

I have created a Loop as above, but how could I add a loop to also save the mean of each sample to a matrix

2 answers

  • answered 2021-11-23 02:21 matheki

    My instinct for this approach is to append mymean to a list in the loop and from there convert the list to any data format you need. I've included how to convert to a matrix from there but you could go to a data.frame as well.

    set.seed(89235)
    values<-c(10, 5, 10, 25, 50, 100, 500, 1000)
    n=length(values)
    mylist = list()
    
    for (i in 1:n){
      mymean<- mean(rnorm(values[i], mean=0, sd=1)) 
      mylist = append(mylist, mymean) # append each iteration of mymean to mylist
      cat("sample size:",values[i],"mean:", mymean, fill=TRUE)
    }
      
    
    matrix(unlist(mylist), ncol =1, nrow =length(mylist))
    

  • answered 2021-11-23 02:22 h45

    You have to firstly define mymean as a vector variable having n elements. Then, store your each mean value at each iteration into mymean's appropriate index. Do not forget to add the index of mymean when printing the result to the console.

    set.seed(89235)
    values <- c(10, 5, 10, 25, 50, 100, 500, 1000)
    n <- length(values)
    mymean <- vector(length = n)
    
    for (i in 1:n){
      mymean[i]<- mean(rnorm(values[i], mean=0, sd=1))  
      cat("sample size:",values[i],"mean:", mymean[i], fill=TRUE)
    }
    
    (mymean)
    

    A simpler approach is to use sapply function.

    set.seed(89235)
    values <- c(10, 5, 10, 25, 50, 100, 500, 1000)
    
    mymean <- sapply(values, function(input) {
      mean.value <- mean(rnorm(input, mean=0, sd=1))  
      cat("sample size:",input,"mean:", mean.value, fill=TRUE)
      return(mean.value)
    })
    
    (mymean)
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum