Home > Net >  How to save a for-loop results
How to save a for-loop results

Time:06-12

I have this 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)

and this script

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

I need to save the result of cmin for each loop of i in another matrix. The result I expect is:

     [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

How can I do? Thank you!

CodePudding user response:

Initialize a vector of length 12 and then assign the output to each element of the vector

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

The vector can be converted to a column matrix by wrapping with matrix

matrix(cmin_out)

This can be done in a efficient vectorized way in base R as well without having to loop - i.e. with max.col

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

CodePudding user response:

Just use sapply() here, like this

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

Output:

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

CodePudding user response:

Just use

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
  • Related