整群抽样中的问题:'mixed with negative subscripts'

Problem in cluster sampling: 'mixed with negative subscripts'

我正在尝试进行整群抽样,但遇到了这个错误: Error in xj[i] : only 0's may be mixed with negative subscripts 原因是什么以及如何解决?感谢您的帮助!

代码如下:

#simulate some data
y <- rnorm(20)
x <- rnorm(20)
z <- rep(1:5, 4)
w <- rep(1:4, each=5)
dd <- data.frame(id=z, cluster=w, x=x, y=y)

clusters <- split(dd, dd$cluster) #split into clusters
k <- length(clusters) #length of clusters
# This function generates a cluster sample
clsamp <- function() dd[unlist(clusters[sample.int(k, k, replace = TRUE)], use.names = TRUE), ]
clsamp()

我收到这个错误:Error in xj[i] : only 0's may be mixed with negative subscripts

找到答案:将分割线改为clusters <- split(seq_len(nrow(dd)), dd$cluster)