使用ave 应用FUNction ID-wise,我们可以重复一个向量1:2 length(ID) 次和sample 它;这可以通过rep_length 完成。为了避免向量总是从 1 开始(从而有利于一个组),我们还对向量进行了采样。
res <- transform(d, g=ave(ID, ID, FUN=function(x)
sample(rep_len(1:2, length(x)))))
res
# ID subject g
# 1 1 101 2
# 2 1 102 1
# 3 1 103 2
# 4 1 104 1
# 5 2 105 1
# 6 2 106 2
# 7 2 107 1
检查一个稍大的数据框:
d2 <- data.frame(ID=rep(1:10, each=7), subject=1:70)
res2 <- transform(d2, g=ave(ID, ID, FUN=function(x)
sample(rep_len(sample(1:2), length(x)))))
with(res2, table(g, ID))
# ID
# g 1 2 3 4 5 6 7 8 9 10
# 1 4 4 3 4 4 3 4 3 4 3
# 2 3 3 4 3 3 4 3 4 3 4
数据:
d <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L), subject = 101:107), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7"))