我有這個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
我能怎么做?謝謝!
uj5u.com熱心網友回復:
就用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
uj5u.com熱心網友回復:
只需使用
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
uj5u.com熱心網友回復:
初始化一個長度為 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491073.html
上一篇:一個“for”回圈,它查看數字并為其分配一個布爾陳述句,它可以比較多個輸入
下一篇:for回圈不采用任何浮點變數