R:不包括一列的列的随机样本

R: random sample of columns excluding one column

我可能发现了之前发布的代码中的一个问题,"R: using foreach() with sample() procedures in randomForest() call" 它与我用来从数据框中抽取列的随机子样本的脚本有关。 假数据(下图)有 19 列,从 "A" 到 "S",我想随机抽取 5 列的子集,但我想从中排除第三列 "C"画。简单地从 sample() 调用的第一个参数中排除第三列是行不通的(即,一些示例包含 'C' 列)。我希望有人对如何执行此操作有建议。这是不起作用的脚本:

randsCOLs= sample(1:dim(FAKEinput[,c(1:2,4:19)])[2], 5, replace=FALSE) 
#randsCOLs= sample(dim(FAKEinput[,c(1:2,4:19)])[2], 5, replace=FALSE) - also doesn't work
out <- FAKEinput[,randsCOLs]

FAKEinput <- 
data.frame(A=sample(25:75,20, replace=T), B=sample(1:2,20,replace=T), C=as.factor(sample(0:1,20,replace=T,prob=c(0.3,0.7))),
    D=sample(200:350,20,replace=T), E=sample(2300:2500,20,replace=T), F=sample(92000:105000,20,replace=T),
    G=sample(280:475,20,replace=T),H=sample(470:550,20,replace=T),I=sample(2537:2723,20,replace=T),
    J=sample(2984:4199,20,replace=T),K=sample(222:301,20,replace=T),L=sample(28:53,20,replace=T),
    M=sample(3:9,20,replace=T),N=sample(0:2,20,replace=T),O=sample(0:5,20,replace=T),P=sample(0:2,20,replace=T),
    Q=sample(0:2,20,replace=T), R=sample(0:2,20,replace=T), S=sample(0:7,20,replace=T))

如果我没记错的话,排除 dim() 调用似乎可行。

randsCOLs = sample(FAKEinput[-3], 5, replace=FALSE) 

这是一个更通用的方法(如果 C 列不是 3rd 列)

FAKEinput[sample(which(names(FAKEinput) !='C'),5, replace=FALSE)]

或者您可以使用 setdiff

FAKEinput[sample(setdiff(names(FAKEinput),'C'), 5, replace=FALSE)]

或者通过更改 1:dim 的 OP 代码并假设 C 是列 3

FAKEinput[sample((1:dim(FAKEinput)[2])[-3], 5, replace=FALSE)]