Creating a new data frame with random variation in r

Viewed 152

I would like to create a new data frame from an existing dataframe where each value is a random variable. More specifically in the new data frame the value (i,j) is a random variable that follows the normal distribution with a mean of (i,j) from the existing dataframe and a standard deviation of 0.1*(i,j).

Below I have done this for one column of a data frame. Is there a way to do this efficiently for all columns of the dataframe? And make the new data frame have the same column names as the existing dataframe?

#data frame with 10 variables
camrysales <- read_excel("camrysales.xlsx", sheet = "10var", skip = 1)

#randomizing Units Sold column
r.camrysales <- rnorm(nrow(camrysales), mean = camrysales$`Units Sold`, sd = 0.1*camrysales$`Units Sold`)
1 Answers

You may do this with lapply -

r.camrysales <- camrysales
r.camrysales[] <- lapply(camrysales, function(x)  rnorm(nrow(camrysales), mean = x, sd = 0.1*x))
r.camrysales

Or using across in dplyr -

library(dplyr)
r.camrysales <- camrysales %>% mutate(across(.fns = ~rnorm(n(), ., 0.1 * .)))
Related