I have a data frame of three columns Distance, Age, and Value where there are three repeated Value for every Distance and Age combination. I would like to generate a random number for Value for certain Distance and Age combinations. I can get a random number to generate however, it is the same random number repeated and I need three different random numbers.
Example Data
set.seed(321)
dat <- data.frame(matrix(ncol = 3, nrow = 27))
colnames(dat)[1:3] <- c("Distance", "Age", "Value")
dat$Distance <- rep(c(0.5,1.5,2.5), each = 9)
dat$Age <- rep(1:3, times = 9)
The code below creates a random number for the Distance and Age combo but the random number is the same for each of the three measurements, they should be different random numbers.
dat$Value <- ifelse(dat$Distance == '0.5' & dat$Age == '1',
rep(rnorm(3,10,2),3), NA)
Instead of getting the same repeated random number for the Distance and Age combo
head(dat)
Distance Age Value
1 0.5 1 13.40981
2 0.5 2 NA
3 0.5 3 NA
4 0.5 1 13.40981
5 0.5 2 NA
6 0.5 3 NA
I would like different random numbers for the Distance and Age combo
head(dat)
Distance Age Value
1 0.5 1 13.40981
2 0.5 2 NA
3 0.5 3 NA
4 0.5 1 11.18246
5 0.5 2 NA
6 0.5 3 NA
The numbers for Value don’t really matter and are for demonstration purposes only.
>Solution :
Replace rep(rnorm(3,10,2),3) with rnorm(nrow(dat), 10, 2).