簡體   English   中英

如何保存for循環結果

[英]How to save a for-loop results

我有這個df:

dx <- structure(list(a = c(0.916290731874155, 2.89037175789616, -0.156004248476581, 
-0.318453731118534, -2.07944154167984, 2.00533356952611, -1.24319351747922, 
0.42744401482694, 1.29532258291416, -2.03292152604494, -0.606135803570316, 
-0.693147180559945), b = c(0.550046336919272, 0.228258651980981, 
-0.577634293438101, 0.135801541159061, 0.644357016390513, -2.30258509299405, 
-0.0870113769896297, 1.71297859137494, 0.17958557697508, -1.65140211153313, 
1.31218638896617, 0.282862786015832), c = c(0.0988458346366325, 
-3.34403896782221, 1.99243016469021, -1.70474809223843, 2.62103882411258, 
2.20727491318972, -1.40242374304977, -1.256836293883, -2.16905370036952, 
2.91777073208428, 0.138586163286146, -0.946143695023836), d = c(0.268263986594679, 
-2.83321334405622, 1.83258146374831, 1.15057202759882, 0.0613689463762919, 
-2.23359222150709, 4.34236137828145, -3.44854350225935, 1.29098418131557, 
-0.356674943938732, -0.21868920096483, -0.810930216216329), e = c(1.65140211153313, 
0.220400065368459, -0.044951387862266, 0.0773866636154201, -1.49877234454658, 
1.36219680954083, -0.295845383090942, -0.709676482511156, -0.916290731874155, 
1.65822807660353, 0.451985123743057, -0.810930216216329)), class = "data.frame", row.names = 2:13)

和這個腳本

output <- t(as.matrix(rep(NA, ncol=1)))
for(i in 1:12) {
    output <- 2*dx[i,]
    cmin <- which.min(output)
}

我需要將每個 i 循環的 cmin 結果保存在另一個矩陣中。 我期望的結果是:

     [1]
[1]   3
[2]   4
[3]   2
[4]   1
[5]   1
[6]   2
[7]   3
[8]   4
[9]   3
[10]  1
[11]  1
[12]  3

我能怎么做? 謝謝!

只需在這里使用sapply() ,就像這樣

as.vector(sapply(1:12, \(i) which.min(2*dx[i,])))

輸出:

[1] 3 3 2 3 1 2 3 4 3 1 1 3

只需使用

as.matrix(apply(dx , 1 , function(x) which.min(2*x)))

   [,1]
1     3
2     3
3     2
4     3
5     1
6     2
7     3
8     4
9     3
10    1
11    1
12    3

初始化一個長度為 12 的向量,然后將output分配給向量的每個元素

cmin_out <- integer(12)
 for(i in 1:12) {
     output <- 2*dx[i,]
     cmin_out[i] <- which.min(output)
 }
cmin_out
 [1] 3 3 2 3 1 2 3 4 3 1 1 3

向量可以通過矩陣換行轉換為列matrix

matrix(cmin_out)

這也可以在base R中以有效的矢量化方式完成,而無需循環 - 即使用max.col

max.col(-dx, 'first')
#[1] 3 3 2 3 1 2 3 4 3 1 1 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM