【问题标题】:How do I find the remaining items in a vector after sampling?采样后如何找到向量中的剩余项目?
【发布时间】:2016-05-29 00:12:00
【问题描述】:

我创建了一个向量如下

Expenditure
 [1] 13.9 15.4 15.8 17.9 18.3 19.9 20.6 21.4 21.7 23.1
[11] 20.0 20.6 24.0 25.1 26.2 30.0 30.6 30.9 33.8 44.1

现在我从Expenditure随机抽取了10个样本

ransomsample <- sample(Expenditure,10)
ransomsample
 [1] 19.9 21.4 20.0 30.0 17.9 25.1
 [7] 26.2 21.7 33.8 13.9

现在我想在创建名为ransomsample 的样本后找到Expenditure 中的剩余项目。我可以使用任何现有的功能吗?

【问题讨论】:

  • 有解决问题的方法吗?
  • 看看help("%in%")
  • 最终你可以通过构造一个逻辑索引向量i &lt;- sample(c(TRUE, FALSE), length(Expenditure), repl=TRUE)来进行采样

标签: r vector random-sample


【解决方案1】:

应该这样做:

#generate 20 random numbers
x <- rnorm(20)
#sample 10 of them
randomSample <- sample(x, 10, replace = FALSE)

#we can get the ones we sampled with:
x[x %in% randomSample]

#Let's confirm this. NOTE - added sort() to easily see they do match
cbind(sort(randomSample), sort(x[x %in% randomSample]))

#So we want to negate the above
x[!(x %in% randomSample)]

【讨论】:

  • 请注意,如果数据中有重复项,这可能不会提供所需的行为。这适用于 OP 中没有重复的示例,但需要谨慎使用这种方法处理具有重复值的数据。这种方法将删除 x 中与样本中的值匹配的所有值,这可能是也可能不是您想要的。
【解决方案2】:

解决此问题的方法取决于您需要如何处理从中采样的向量中的重复。如果您可以确定没有重复,那么@Chase 使用x[!(x %in% randomSample)] 给出的简单方法是完美的。 但是,如果可能存在重复,则需要更加小心。我们可以在下面清楚地看到这一点:

# Start with a vector (length=9) replete with replicates
x <- rep(letters[1:3],3)

# Now sample 8 of its 9 values (leaving one unsampled)
set.seed(123)
randomSample <- sample(x, 8, replace = FALSE)

# try using simple method to find which value remains after sampling
x[!(x %in% randomSample)]
## character(0)

这个简单的方法失败了,因为%in% 匹配了x 中所有 个采样值。如果这是您想要的,那么这就是适合您的方法。但是,如果您想知道采样后每个值还有多少,那么我们需要换一条线。

有几种方法,但可能最优雅的方法是从初始向量的频率表中减去样本的频率表,以提供剩余未采样值的表。然后从这个表中生成一个未采样值的向量。

xtab <- as.data.frame(table(x))
stab <- as.data.frame(table(randomSample))
xtab[which(xtab$x %in% stab$randomSample),]$Freq <- 
  xtab[which(xtab$x %in% stab$randomSample),]$Freq - stab$Freq
rep(xtab$x, xtab$Freq)
## [1] a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多