首页 > 解决方案 > 我希望 r 在向量中安排/合并我的重采样

问题描述

我有一个从 1 到 10 的向量,我将其分成每个大小为 2 的块,然后对这些块重新采样,但我对 r 中的结果排列不满意。下面的r代码展示了我的经验:

ts <- 1:10 # generate a number from 1 to 10
bs <- 2 # let block size equals 2
nb <- length(ts) / bs # number of blocks
blk <- split(ts, rep(1:nb, each=bs)) # split  the generated numbers into "blk"
res<-sample(blk, replace=T, 20) # resample the blk 20 times with replacement
res # gives me the below result

#$`5`
#[1]  9 10

#$`5`
#[1]  9 10

#$`5`
#[1]  9 10

#$`3`
#[1] 5 6

#$`1`
#[1] 1 2

#$`2`
#[1] 3 4

#$`5`
#[1]  9 10

#$`1`
#[1] 1 2

#$`1`
#[1] 1 2

#$`1`
#[1] 1 2

#$`4`
#[1] 7 8

#$`4`
#[1] 7 8

#$`4`
#[1] 7 8

#$`4`
#[1] 7 8

#$`4`
#[1] 7 8

#$`3`
#[1] 5 6

#$`2`
#[1] 3 4

#$`1`
#[1] 1 2

#$`1`
#[1] 1 2

#$`1`
#[1] 1 2

我宁愿想要这样的结果:

(9,10,9,10,9,10,5,6,1,2,3,4,9,10,1,2,1,2,1,2,7,8,7,8,7 ,8,7,8,7,8,5,6,3,4,1,2,1,2,1,2)

这样我就可以将“res”称为单变量,并且我应该能够将结果写入一行或一列.csv文件,如下所示:

write.csv(res, "resamples.csv")

标签: rrandomsplit

解决方案


您可以使用unlist()扁平化列表结构。如果您不想要/不需要它们,也可以删除自动生成的名称:

ts <- 1:10 # generate a number from 1 to 10
bs <- 2 # let block size equals 2
nb <- length(ts) / bs # number of blocks
blk <- split(ts, rep(1:nb, each=bs)) # split  the generated numbers into "blk"
res<-unlist(sample(blk, replace=TRUE, 20)) # resample the blk 20 times with replacement
names(res) <- NULL # optional
res
#>  [1]  3  4  9 10  1  2  7  8  3  4  3  4  7  8  5  6  7  8  3  4  1  2  3
#> [24]  4  9 10  5  6  7  8  9 10  9 10  5  6  9 10  1  2

reprex 包(v0.3.0)于 2019 年 9 月 23 日创建


推荐阅读