在组内创建一个具有常量值的随机数
Creating a random number with constant value within groups
我正在创建一个随机数,其中特定组的每个成员都具有相同的变量值。我找到了解决方案,但我怀疑它不是很有效。我想知道是否有人有办法在一行代码中做到这一点:
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))
单行使用 ave
。
res <- transform(mtcars, rand=ave(cyl, cyl, FUN=\(x) runif(1)))
检查:
with(res, tapply(rand, list(cyl), var))
# 4 6 8
# 0 0 0
我正在创建一个随机数,其中特定组的每个成员都具有相同的变量值。我找到了解决方案,但我怀疑它不是很有效。我想知道是否有人有办法在一行代码中做到这一点:
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))
单行使用 ave
。
res <- transform(mtcars, rand=ave(cyl, cyl, FUN=\(x) runif(1)))
检查:
with(res, tapply(rand, list(cyl), var))
# 4 6 8
# 0 0 0