简体   繁体   中英

How can I store rnorm output from a loop in a separate vector?

I need to store the output into a separate vector so that I can plot the data ( years against reproduction_rate ). At the moment it only stores the final year and not years 1:20. Is there a way to use grep/regex to store the output values into one external vector instead of copying and pasting from the console?

N <- 1000 
years <- 1:20 
storage <- ()
for (year in years)  {
  reproduction_rate <- rnorm(n=1, mean=1, sd=0.4)+N
  phrase <- paste("In year", year, "the population rate was", reproduction_rate)
  print(paste("In year", year, "the population rate was", reproduction_rate))
  storage <- (reproduction_rate)
}

If you can forgo the printing,

storage <- rnorm(n=20, mean=1, sd=0.4)+N

will work. Otherwise,

storage <- numeric(length(years)) 
for (i in seq_along(years)) {
    storage[i] <- rnorm(...)
    print("stuff",years[i],...)
}

As long as you set the seed appropriately, and don't run any other commands in between that call the random number generator, you're guaranteed to get exactly the same answers whether you pick the random numbers all at once or one at a time. All at once:

N <- 1000
nyear <- 20
years <- 1:nyear
set.seed(101)
storage1 <- rnorm(n=nyear, mean=1, sd=0.4)+N
for (i in seq_along(years)) {
   print(paste("year",years[i],": reproduction=",storage1[i]))
}

One at a time:

set.seed(101)
storage2 <- numeric(nyear)
for (i in seq_along(years)) {
   storage2[i] <- rnorm(1,mean=1,sd=0.4)+N
   print(paste("year",years[i],": reproduction=",storage2[i]))
}

Compare:

all.equal(storage1,storage2)  ## TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM