对 R 中的数据帧列表进行采样
Sample a list of dataframes in R
我有一个由 16 个数据帧组成的列表 (dientes
)。我想在每个数据帧中对 80% 的行进行采样而不进行替换。我尝试使用这些 lapply()
函数但没有成功:
index <- lapply(1:nrow(dientes), sample, round(0.8*nrow), replace = F)
index <- lapply(dientes, sample, round(0.8*nrow), replace = F)
我哪里错了?
如果 index
应包含采样列表 data.frames,您可以这样做:
## mock list of data.frames
dientes <- list(A=mtcars, B=iris, C=volcano)
## count input rows
lapply(dientes, nrow)
#> $A
#> [1] 32
#>
#> $B
#> [1] 150
#>
#> $C
#> [1] 87
index <- lapply(dientes, function(x) x[sample(nrow(x), round(0.8*nrow(x))), ])
## count output rows
lapply(index, nrow)
#> $A
#> [1] 26
#>
#> $B
#> [1] 120
#>
#> $C
#> [1] 70
由 reprex package (v0.3.0)
于 2020-03-18 创建
我会做以下事情:
index <- lapply(dientes, function(x){x[sample(x, round(0.8*nrow(x)), replace = F),]})
lapply 将列表 dientes
作为输入
function(x){..}
对每个元素应用你想要的操作
x
是每个元素,您使用 x[sample(...),]
从中获取行
我有一个由 16 个数据帧组成的列表 (dientes
)。我想在每个数据帧中对 80% 的行进行采样而不进行替换。我尝试使用这些 lapply()
函数但没有成功:
index <- lapply(1:nrow(dientes), sample, round(0.8*nrow), replace = F)
index <- lapply(dientes, sample, round(0.8*nrow), replace = F)
我哪里错了?
如果 index
应包含采样列表 data.frames,您可以这样做:
## mock list of data.frames
dientes <- list(A=mtcars, B=iris, C=volcano)
## count input rows
lapply(dientes, nrow)
#> $A
#> [1] 32
#>
#> $B
#> [1] 150
#>
#> $C
#> [1] 87
index <- lapply(dientes, function(x) x[sample(nrow(x), round(0.8*nrow(x))), ])
## count output rows
lapply(index, nrow)
#> $A
#> [1] 26
#>
#> $B
#> [1] 120
#>
#> $C
#> [1] 70
由 reprex package (v0.3.0)
于 2020-03-18 创建我会做以下事情:
index <- lapply(dientes, function(x){x[sample(x, round(0.8*nrow(x)), replace = F),]})
lapply 将列表 dientes
作为输入
function(x){..}
对每个元素应用你想要的操作
x
是每个元素,您使用 x[sample(...),]