我有一个10x3 NA矩阵,该矩阵用1-100之间的随机数填充一个随机行。我想选择另一个随机行(可以说不用替换)并填充它,而又不知道最初填充的是哪一行。我不确定如何进行第二选择。我想我将必须找到一种方法来将子集仅包含NA的行,然后随机选择。如果您需要详细信息,请告诉我。
myData <- matrix(data = NA,10,3)
random row selection.
myData[sample(1:10,size = 1,),] <- c(sample(1:100,size = 1,replace = TRUE),sample(1:100,size = 1,replace = TRUE),sample(1:100,size = 1,replace = TRUE))
不确定第二次随机选择
答案 0 :(得分:0)
您实际上不需要单独存储子集。都可以在while
循环中处理:
myData <- matrix(data = NA,10,3)
while(sum(is.na(myData))>0){ ## while there are NAs
if (sum(is.na(myData)[,1])>1){ ## if it is not the last row (because the last row will need differetn approach being a vector, and not a matrix)
myData[is.na(myData)[,1],][ ## from the subset of NAs whose first column (and hence all of it) is not NA
sample(1:nrow(myData[ ## choose one randomly
is.na(myData)[,1],] ),size = 1),] = sample(1:100,size = 3,replace = TRUE) ## substitute it by a random vector of the same length
} else { ## for the last one
myData[is.na(myData)[,1],]= sample(1:100,size = 3,replace = TRUE)
}
}