Home > Net >  Forloop using variable name to fill array in R
Forloop using variable name to fill array in R

Time:10-04

within a function in R I need to fill in a specific array. It is working when I write out all the lines one by one by hand, but I was wondering if it is possible to use a forloop, as the array will be way bigger than the example below.

A simplified example of what I try to do:

dt <- data.frame(prob_name = c("q_1", "q_2", "p_1", "p_2", "p_3"),
                           prob=c(100,200,0.07, 0.08, 0.09))
dt <- setNames(data.frame(t(dt[,-1])), dt[,1])

trans_mat <- array(0, dim = c(2, 2, 3))

for (i in 1:nrow(dt)) {
  trans_mat[1, 2, i] <- p_i
  }      

I want those specific places in the array to be filled with the corresponding probability, so the array will be

1) 0, 0.07
   0, 0
2) 0, 0.08
   0, 0

etc

Is there a way to do this with a forloop (as the forloop is not recognizing the "i" in "p_i"), or do I have to write this all out like

trans_mat[1,2,1] <- p_1 

Thanks in advance!

CodePudding user response:

Loop over the sequence of third dimension of 'trans_mat' instead of the nrow of 'dt' as number of rows of dt is just 1., then extract ([[) the column 'p_', i, by pasteing and do the assignment

for(i in seq(dim(trans_mat)[3])) trans_mat[1, 2, i] <- dt[[paste0("p_", i)]]

-output

> trans_mat
, , 1

     [,1] [,2]
[1,]    0 0.07
[2,]    0 0.00

, , 2

     [,1] [,2]
[1,]    0 0.08
[2,]    0 0.00

, , 3

     [,1] [,2]
[1,]    0 0.09
[2,]    0 0.00

CodePudding user response:

Using replace in sapply.

sapply(dt[1, 3:5], \(x) replace(array(0, c(2, 2)), 3, x), simplify='array')
# , , p_1
# 
# [,1] [,2]
# [1,]    0 0.07
# [2,]    0 0.00
# 
# , , p_2
# 
# [,1] [,2]
# [1,]    0 0.08
# [2,]    0 0.00
# 
# , , p_3
# 
# [,1] [,2]
# [1,]    0 0.09
# [2,]    0 0.00

Data:

dt <- structure(list(q_1 = 100, q_2 = 200, p_1 = 0.07, p_2 = 0.08, 
    p_3 = 0.09), class = "data.frame", row.names = c(NA, -1L))
  • Related