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

Asked

Viewed 52 times

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 give values normally distributed 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 was at the end k*m (the number of rounds * the sample generated in each one).

UPDATING

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 have managed to generate everything I needed in k different data.frames, the problem is to unite all Dfs.

2 answers

5

You can use it that 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)

3


Well, I was able to solve it before Mr Fernandes replied. 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.