Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R list keeps returning NAs, how can I fix?

I’m not really sure why I’m receiving multiple NA values from this loop despite getting the correct values when I manually multiply the individual list values, and would appreciate any help fixing this code.

q = 5
B_theta = 7.32
B_B = c(1,2,3,4,5,6,7,8,9,10)
Z_t = c(1,2,3,4,5,6,7,8,9,10)
x_t = function (B_theta,B_B,Z_t){ > #function in question
  XX_t = c()
  for (k in q){
      XX_t[k] = B_theta*B_B[k]*Z_t[k]
  }
  return(XX_t)
}
big_I = x_t(B_theta,B_B,Z_t)
big_I
# returns NA NA NA NA 183

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2 options. The first one is to append elements to a vector such as below:

x_t = function (B_theta,B_B,Z_t){
    XX_t = c()
    for (k in 1:q){
      XX_t <- c(XX_t, B_theta*B_B[k]*Z_t[k])
    }
    return(XX_t)
}
big_I = x_t(B_theta,B_B,Z_t)
> big_I
[1]   7.32  29.28  65.88 117.12 183.00

The second option uses a list and should be faster for large data.

x_t = function (B_theta,B_B,Z_t){
  XX_t = list()
  for (k in 1:q){
    XX_t[[k]] <- B_theta*B_B[k]*Z_t[k]
  }
  return(unlist(XX_t))
}
big_I_list = x_t(B_theta,B_B,Z_t)

identical(big_I, big_I_list)
[1] TRUE

Note that indeed your for loop was most probably not correctly defined (only one element).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading