r - 我希望 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")
解决方案
您可以使用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 日创建
推荐阅读
- xcode - xcode 命令行将屏幕截图、描述和元数据上传到 itunesconnect
- sql-server - 将事实表的子集用于另一个事实表?
- python - Keras预测一个数字,如果在一个范围内则通过
- python - 如何将类中的变量变成全局变量以备后用?
- spring - 如何使用具有多线程的 JdbcCursorItemReader 从 Oracle Db 读取数据
- ios - 如何更改 tableview willDisplay 函数中的布局和属性设置?
- java - 比较休眠条件中的浮点值
- qt - 如何使部分区域透明而其余部分显示半透明?
- laravel - 带有html2canvas的Laravel不保存图片
- amazon-dynamodb - 当 GetItem 结果为空时,Dynamodb 的 AWS DAX 是否会缓存空结果?