首页 > 解决方案 > 获取与引导采样的唯一值相对应的数据帧的索引

问题描述

我想找到与我的数据替换值采样对应的数据帧的索引,并且我希望索引也被过采样。由于过采样,which不起作用。循环很foreach简单,但太慢了。这是一个虚拟示例:

  library(foreach)
  library(dplyr)
  # sample unique values of a variable, with replacement
  samp <- sample(unique(mtcars$carb), replace = TRUE)
  # using which doesn't account for oversampling
  which(mtcars$carb %in% samp) 
  # here's what I want to do, but in a slow loop
  foreach(i = samp, .combine = c) %do% {which(mtcars$carb == i)} 

有没有一种方法可以根据重复值获取重复索引,从而避免循环?

标签: r

解决方案


编辑

使用find.matchesfrom Hmiscpackage 以不同的顺序给出相同的结果。但我不确定你的方法是否已经更快了。

set.seed(123)
data <- floor(runif(20) * 10)
smpl <- sample(data, 10, replace = T)
matches <- Hmisc::find.matches(smpl, data)$matches
matches[matches > 0] %>% unlist

[1] 6  7 13  5  7 15  5  3  6  3 18  9 11  9 11 10 18 10 14 20 14 20 12 12

使用您的foreach

foreach(i = smpl, .combine = c) %do% {which(data == i)}

[1]  6 18  7  9 14 13  5 11 20  7  9 14 15  5 11 20  3 10 12  6 18  3 10 12

推荐阅读