Home > Software design >  How to create a vector that sums random numbers generated repeatedly?
How to create a vector that sums random numbers generated repeatedly?

Time:10-05

Goal

I want to see how random profits/losses can accumulate over time.

library(dplyr)

names <- seq(1:1000)
wealth <- rep(0, 1000)
df <- as.data.frame(bind_cols(names, wealth)) 
colnames(df) <- c("households", "wealth")
View(df)

Attempt

df2 <- df %>% 
    mutate(new_wealth = runif(1000,-10,10),
           new_wealth2 = runif(1000,-10,10),
           final_wealth = wealth   new_wealth new_wealth2) %>% 
  select(households, final_wealth)

Solution Wanted

Instead of creating loads of "new_wealth" columns, I want to add a vector of random numbers to the final_wealth column, say 100 times, and then see the result. Ideally, I would do it 1000 times.

I don't care about the new_wealth columns, and just want the final_wealth column. Can I use lapply to do this? If not, do any of you have a better solution?

Thanks!

CodePudding user response:

We can use replicate to repeat the runif code any number of times. Use rowSums to perform the sum and add a new column.

n <- nrow(df)
n_repeat <- 100
df$final_wealth <- rowSums(replicate(n_repeat, runif(n,-10,10)))

CodePudding user response:

We can use tidyverse

library(dplyr)
library(purrr)
df1 <- df %>% 
       mutate(final_wealth = rerun(100, runif(n(), -10, 10)) %>%
             reduce(` `))
  • Related