R:制作2个子集向量,以使值在索引方向上不同 [英] R: make 2 subset vectors so that values are different index-wise
问题描述
我想用相同的数据制作两个向量子集,并使用 replace = TRUE
。
I want to make 2 vectors subsetting from the same data, with replace=TRUE
.
即使两个向量都可以包含相同的值,但在相同的索引位置上它们不能相同。
Even if both vectors can contain the same values, they cannot be the same at the same index position.
例如:
> set.seed(1)
> a <- sample(15, 10, replace=T)
> b <- sample(15, 10, replace=T)
> a
[1] 4 6 9 14 4 14 15 10 10 1
> b
[1] 4 3 11 6 12 8 11 15 6 12
> a==b
[1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
在这种情况下,向量 a
和 b
在索引1(value == 4)包含相同的值,即出于我的目的,这是错误的。
In this case, vectors a
and b
contain the same value at index 1 (value==4), which is wrong for my purposes.
有没有简单的方法可以纠正此错误?
Is there an easy way to correct this?
子集
步骤?
还是应该逐个循环检查元素的值,如果值相同,再选择 b [i]
并再次检查它是否不相同 ad infinitum ?
Or should I go through a loop checking element by element and if the values are identical, make another selection for b[i]
and check again if it's not identical ad infinitum?
非常感谢!
推荐答案
我的想法是,获得10个长度为10的样本而不是替换,获得10个长度2无需替换
My idea is, instead of getting 2 samples of length 10 with replacement, get 10 samples of length 2 without replacement
library(purrr)
l <- rerun(10,sample(15,2,replace=FALSE))
l
中的每个元素是长度为2的整数的向量。保证这两个整数是不同的,因为我们在 sample
Each element in l
is a vector of integers of length two. Those two integers are guaranteed to be different because we specified replace=FALSE
in sample
# from l extract all first element in each element, this is a
a <- map_int(l,`[[`,1)
# from list extract all second elements, this is b
b <- map_int(l,`[[`,2)
这篇关于R:制作2个子集向量,以使值在索引方向上不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!