如果我有一个任意长度的字符串向量说;
vec <- c("a","b","c","d","e","f","g","h","i")
Run Code Online (Sandbox Code Playgroud)
我正在寻找一个函数,使用下面显示的策略从该向量中采样n个值.显示数字,因为很难解释.
function call:
result:
schematic diagram:
fn(vector=vec,n=1)
"a"
|
a b c d e f g h i
fn(vector=vec,n=2)
"a" "i"
_______________
| |
a b c d e f g h i
fn(vector=vec,n=3)
"a" "e" "i"
_______________
| | |
a b c d e f g h i
fn(vector=vec,n=4)
"a" "c" "g" "i"
_______________
| | | |
a b c d e f g h i
fn(vector=vec,n=5)
"a" "c" "e" "g" "i"
_______________
| | | | |
a b c d e f g h i
Run Code Online (Sandbox Code Playgroud)
抽样不一定准确.值可以来自大致正确的区域,但必须一致.字符串向量可以是偶数或奇数.
一种方法是使用seq(),利用它的length.out=论点来获得你寻求的均匀间隔的指数:
fn <- function(x, n) {
x[round(seq(1,length(x), length.out=n))]
}
## Check that it works
fn(vec, 1)
# [1] "a"
fn(vec, 2)
# [1] "a" "i"
fn(vec, 4)
# [1] "a" "d" "f" "i"
fn(vec, 8)
# [1] "a" "b" "c" "d" "f" "g" "h" "i"
Run Code Online (Sandbox Code Playgroud)