Home > Enterprise >  Creating a random number with constant value within groups
Creating a random number with constant value within groups

Time:12-27

I'm creating a random number where each member of a specific group has the same value of the variable. I found a solution but I suspect it isn't very efficient. I'm wondering if anyone anyone has a way to do this in one line of code:

library(dplyr)
data(mtcars)

t1 <- Sys.time() #Can the next two lines be replaced by one?

a <- data.frame(random = runif(3, 0, 6),
                cyl = seq(4,8,2))

merged <- merge(mtcars, a, by = 'cyl')
t2 <- Sys.time()
t2 - t1
#check to make sure it worked
merged %>%
  group_by(cyl) %>%
  summarise(across(random, sd))

CodePudding user response:

One-liner using ave.

res <- transform(mtcars, rand=ave(cyl, cyl, FUN=\(x) runif(1)))

Check:

with(res, tapply(rand, list(cyl), var))
# 4 6 8 
# 0 0 0 
  • Related