Home > Mobile >  R nested for loops
R nested for loops

Time:03-09

I am trying to do a nested for loop in R and am a bit confused on how to make it work. I want to assign rows 1:4 of matrix m based upon a function of i. Below I have generalization of my current code. I believe I need to double loop as my actual code for i depends on the values 5, 10, 15, 25.

f <- function()
m <- matrix(nrow = 4)
for (i in c(5, 10, 15, 25)) {
for (j in c(1:4)) {
    m[j,1] <- f(i)
}
}

which results in:

> m
     [,1]
[1,]  f(25)
[2,]  f(25)
[3,]  f(25)
[4,]  f(25)

My desired output is below and I'm not sure how to do the loop to produce these results.

> m
     [,1]
[1,]  f(5)
[2,]  f(10)
[3,]  f(15)
[4,]  f(25)

CodePudding user response:

I think doing a nested for-loop would be hard so I ended up doing:

f <- function()
sapply(c(5, 10, 15, 25), f) %>%
  matrix()
  • Related