聚类抽样中的问题:“与负下标混合”

问题描述

我试图进行集群抽样,但遇到了这个错误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)