Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Different random numbers when two conditions are met in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading