我正在創建一個亂數,其中特定組的每個成員都具有相同的變數值。我找到了一個解決方案,但我懷疑它不是很有效。我想知道是否有人有辦法在一行代碼中做到這一點:
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))
uj5u.com熱心網友回復:
單行使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/394680.html
