r-用于具有多个输出的环路



我有一个大致如下的数据帧:

dput(df)
structure(list(a = 1:9000, b = 1:9000, c = 1:9000, d = 1:9000, 
e = 1:9000, f = 1:9000, g = 1:9000, h = 1:9000, i = 1:9000), class = "data.frame", row.names = c(NA, 
-9000L))

编辑:这些是精确的值,这只是为了显示粗略的尺寸,还有更多的列,这些值不仅仅运行1:9000

随机采样&加上一列我一直在使用的行平均值:

sample_1 <- sample(1:9000, 200, replace=F)
sampled_df_1 <- df[c(sample_1),]
sampled_df_1$Means_1 <- rowMeans(sampled_df_1)

我需要重复做100次,然后创建一个均值的数据帧。我想我需要使用for循环,如下所示:

for(i in 1:100){
sample_[i] <- sample(1:9000, 200, replace=F)
sampled_df_[i] <- df[c(sample_[i]),]
sampled_df_[i]$Means_[i] <- rowMeans(sampled_df_[i])}

但是[i]没有附加矢量号。我也试过{I}和'+I'这样做可能吗?我认为assign(paste(((可能是这里的关键,但我正在努力当我过去的时候,有没有一种简单的方法可以创建一个只包含means列的数据框架,而不需要键入它们的所有名称?

使用sapply()会更简单,因为它会同时执行两次迭代并将结果进行组合。

set.seed(42)
df <- data.frame(a = rnorm(6), b = rnorm(6), c = rnorm(6))
df
#>            a           b          c
#> 1  1.3709584  1.51152200 -1.3888607
#> 2 -0.5646982 -0.09465904 -0.2787888
#> 3  0.3631284  2.01842371 -0.1333213
#> 4  0.6328626 -0.06271410  0.6359504
#> 5  0.4042683  1.30486965 -0.2842529
#> 6 -0.1061245  2.28664539 -2.6564554
set.seed(43)
N_REPEATS <- 4
N_ROWS_SAMPLED <- 3
sapply(seq_len(N_REPEATS), function(i) {
rowMeans(df[sample(nrow(df), N_ROWS_SAMPLED), ])
})
#>         [,1]       [,2]       [,3]       [,4]
#> 4  0.4020330 -0.3127153  0.4749617 -0.1586448
#> 6 -0.1586448  0.4749617 -0.3127153  0.4978732
#> 1  0.4978732 -0.1586448  0.7494103  0.4020330

如果您想保留采样的子集,请将其分为两部分:

set.seed(43)
samples <- lapply(seq_len(N_REPEATS), function(i) {
df[sample(nrow(df), N_ROWS_SAMPLED), ]
})
sapply(samples, rowMeans)
#>         [,1]       [,2]       [,3]       [,4]
#> 4  0.4020330 -0.3127153  0.4749617 -0.1586448
#> 6 -0.1586448  0.4749617 -0.3127153  0.4978732
#> 1  0.4978732 -0.1586448  0.7494103  0.4020330

使用for()循环可以这样完成:

df <- structure(list(a = 1:9000, b = 1:9000, c = 1:9000, d = 1:9000, 
e = 1:9000, f = 1:9000, g = 1:9000, h = 1:9000, i = 1:9000), class = "data.frame", row.names = c(NA, 
                                          -9000L))
nsims <- 100
sample_df_rows <- 200
Row <- seq(1:sample_df_rows)
output <- data.frame(Row)
for(i in 1:nsims){
sample <- sample(1:9000, sampled_df_rows, replace=F)
sample_df <- df[c(sample),]
sample_df$Means <- rowMeans(sample_df)
colnames(sample_df) <- c(letters[1:9],paste0("Means_",i))
output <- cbind(output,sample_df[10])
}
output

最新更新