r - 获取与引导采样的唯一值相对应的数据帧的索引
问题描述
我想找到与我的数据替换值采样对应的数据帧的索引,并且我希望索引也被过采样。由于过采样,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)}
有没有一种方法可以根据重复值获取重复索引,从而避免循环?
解决方案
编辑
使用find.matches
from Hmisc
package 以不同的顺序给出相同的结果。但我不确定你的方法是否已经更快了。
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
推荐阅读
- java - Spring Boot mvc 蚂蚁映射
- python - Python 字符串 - 字符串的不变性
- vb.net - WebBrowser 在导航到 url 时出现错误
- python - 气流插件操作员未运行执行方法
- c# - Web 服务在我的电脑上工作,但在服务器电脑上不起作用
- mysql - 如何从 MySQL TinyInt(1) 返回 NULL 而不是 0
- spring - 使用 Jasypt 加密数据库密码导致 NoClassDefFoundError
- c# - ASP.NET 中的列表
- okta - Okta React 为每个请求加载太多 iframe
- python - 深度神经网络的批量缩放