How does a forloop generate random values, then "append" the next set of generated values?

2
k <- 8
m = 100

for (i in 1:k){
  x <- rnorm(mean = i, 
          sd = .5, 
            n=m)
  y <- rnorm(mean = (8-i),
          sd = .5,
            n=m)
  amostra2 <- data.frame(x,y)
   }

This is the code I have. Given k and m, I generate normally distributed values and save them in a data frame. The problem is that this way the loop only rewrites the values of x and y, when I wanted to "append" them, so that the length of each vector is at the end k * m (the number of rounds * the sample generated in each ).

UPDATE

for (i in 1:k){

x <- rnorm(mean = i, 
          sd = .5, 
            n=m)
y <- rnorm(mean = (8-i),
          sd = .5,
            n=m)
assign(paste("amostra_for_",i, sep=""), 
     value = data.frame(x,y)) 
}

for (i in 2:k) {
amostra2 <- rbind(amostra_for_1, 
                paste("amostra_for_",i))
}

Now I was able to generate everything I needed in different data.frames k, the problem is to merge all the DFs.

    
asked by anonymous 16.08.2018 / 05:20

2 answers

3

Well, I was able to solve it before colleague Fernandes responded. Here is a solution:

datalist = list() ## Util depois para aglutinar os dados

for (i in 1:k){

x <- rnorm(mean = i, 
          sd = .1, 
            n=m)

y <- rnorm(mean = (8-i),
          sd = .1,
            n=m)

datalist[[i]] <- data.frame(x,y)
}

amostra2 <- do.call(rbind, datalist)
    
16.08.2018 / 06:11
5

You can use it this way

k = 8
m = 100

create_empty_table <- function(num_rows, num_cols) {
  frame <- data.frame(matrix(NA, nrow = num_rows, ncol = num_cols))
  return(frame)
}

amostra = create_empty_table(100, 2*8)

for (i in 1:k){  
  amostra[,(2*i)-1] <- rnorm(mean = i, sd = .5, n=m)
  amostra[,(2*i)] <- rnorm(mean = (8-i), sd = .5, n=m)
}

colnames(amostra) = rep(c('x' ,'y'), 8)
    
16.08.2018 / 06:09