Home > Enterprise >  R list keeps returning NAs, how can I fix?
R list keeps returning NAs, how can I fix?

Time:07-18

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

CodePudding user response:

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).

CodePudding user response:

A loop isn't needed here because R is optimized for vectors multiplication :

x_t = function (B_theta,B_B,Z_t,q){
  B_theta * B_B[1:q]*Z_t[1:q]
}

x_t(B_theta,B_B,Z_t,q)
#[1]   7.32  29.28  65.88 117.12 183.00
  • Related