【问题标题】:Random subset/sample of dataframe数据帧的随机子集/样本
【发布时间】:2015-02-22 21:06:03
【问题描述】:

我对如何对数据框进行采样有疑问。数据集是这样的:

114 行 9 列。我需要提取 3 个子集,每个子​​集都是 38 行 (114 / 3)。

我有这个脚本,但它不适用于最后一个子集:

install.packages("Rcmdr")
library(Rcmdr)

ana <- read.delim("~/Desktop/ana", header=TRUE, dec=",")

set1 <- ana[sample(nrow(ana), 38), ]
set1.index <- as.numeric(rownames(set1))

ana2 <- ana[(-set1.index),]
set2 <- ana2[sample(nrow(ana2), 38), ]
set2.index <- as.numeric(rownames(set2)) 

ana3 <- ana2[(-set2.index),]
ana3

对于 set1 和 set2,我得到了正确的子集,但对于 set3,我得到了 50 行(或更少)。

(提前谢谢!=))

【问题讨论】:

  • 欢迎来到 StackOverflow!请阅读how to provide your data in a reproducible format,以便我们更轻松地为您提供帮助。以图像的形式提供数据会使您难以快速使用示例代码,因此请考虑构建一个假数据集并使用dput 提供它。
  • 您似乎希望每一行都恰好位于其中一个子集中。这是一个示例,您可以如何使用 iris 数据集来做到这一点。 set_number &lt;- sample(1:3, nrow(iris), replace = TRUE); set1 &lt;- iris[set_number == 1, ]; set2 &lt;- iris[set_number == 2, ]; set3 &lt;- iris[set_number == 3, ] 或 my_sets &lt;- split(iris, set_number)

标签: r subset sample


【解决方案1】:

通常@docendodiscimus 提供有效的建议,但他提供的采样代码不能保证子集中的数量相等(见下文)。试试这个:

 set.seed(123) # best to set a seed to allow roproducibility
 sampidx <- sample( rep(1:3, each=38)
 set1 <- ana[sampidx==1, ]  # logical indexing of dataframe
 set2 <- ana[sampidx==2, ]
 set3 <- ana[sampidx==3, ]

使用替换的样本缺乏均分:

> table( sample(1:3, nrow(iris), replace = TRUE) ) 
 1  2  3 
52 52 46 
> table( sample(1:3, nrow(iris), replace = TRUE) )

 1  2  3 
51 49 50    # notice that it also varies from draw to draw
> table(sampidx)
sampidx
 1  2  3 
38 38 38 

【讨论】:

  • 非常感谢 BondedDust,这正是我想要的!也感谢你的 docendodiscimus! =)
猜你喜欢
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-05-21
  • 2014-09-15
  • 1970-01-01
  • 2015-08-16
相关资源
最近更新 更多