将问题提炼成函数术语:
给定值列表(让我们使用字母)
uniqueList <- letters[1:9]以及该列表中随机组合的4列数据帧,其中一些重复(这里使用combn生成我的数据的合理传真,但我的数据来自用户输入的数据)
data <- t(combn(uniqueList,4))如何标识和选择该数据集中的最小行数(及其索引),以使列表中的每个值至少出现一次,而不管它出现在哪一列中?
在我试图解决的实际问题中,我需要从真实数据中生成最小数量的样本记录,以便我在4列中至少有一次值列表中的每个唯一值。
发布于 2017-07-25 04:55:17
也许这能行得通
#Split `data` into rows and then convert to vector
temp = do.call(c, lapply(1:NROW(data), function(i) data[i,]))
#Advance along `temp` and see if `unique` gives all elements of uniqueList
#Extract the first index where that happens
ind = which(sapply(1:length(temp), function(i) identical(unique(temp[1:i]), uniqueList)))[1]
#Divide the ind by number of column to obtain row number
myrow = ceiling(ind/NCOL(data))
myrow
#[1] 6
identical(sort(unique(as.vector(data[1:myrow,]))), uniqueList)
#[1] TRUEhttps://stackoverflow.com/questions/45289688
复制相似问题