R:不包括一列的列的随机样本 [英] R: random sample of columns excluding one column

查看:47
本文介绍了R:不包括一列的列的随机样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能已经发现了之前发布的代码中的一个问题,R:在 randomForest() 调用中使用 foreach() 和 sample() 过程",它与我用来绘制随机子样本的脚本有关数据框中的列.假数据(如下)有 19 列,从A"到S",我想绘制 5 列的随机子集,但我想从绘制中排除第三列C".简单地从 sample() 调用的第一个参数中排除第三列是行不通的(即,某些示例包含C"列).我希望有人对如何做到这一点提出建议.这是不起作用的脚本:

I may have discovered one of the problems in the code posted previously, "R: using foreach() with sample() procedures in randomForest() call" and it relates to the script I was using to draw a random subsample of columns from a dataframe. The fake data (below) has 19 columns, "A" through "S" and I want to draw a random subset of 5 columns, but I want to exclude the third column, "C", from the draw. Simply excluding the third column from the first argument of sample() call does not work (i.e., some of the samples contain the 'C' column). I'm hoping someone has a suggestion on how to do this. This is the script that does not work:

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() 调用会起作用.

It looks like excluding the dim() call will work, if I'm not mistaken.

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

这篇关于R:不包括一列的列的随机样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆