Andres Mora
Andres Mora

Reputation: 1106

How to store a NULL value in a vector?

Im running an API script from R which returns a numeric value everytime is called. Im storing that value on a vector using a loop

i=1
a=""
idPaciente = NULL
for (i in 1:length (poblacion1)) {

  
  a = consulta_idPaciente(poblacion1[i])
  print(a)
  idPaciente[i] <- a 

  }

Sometimes the API will return a NULL value when there is no output from the server for that specific API input. this is causing the following error

NULL
Error in idPaciente[i] <- a : replacement has length zero

I would like to store the NULL anyways in the vector since that absense of data means something to me.

Upvotes: 1

Views: 680

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You can check for NULL values and assign NA to the output.

i=1
a=""
idPaciente = numeric(length(poblacion1))

for (i in seq_along(poblacion1)) {
  a = consulta_idPaciente(poblacion1[i])
  if(is.null(a)) idPaciente[i] <- NA
  else idPaciente[i] <- a
}

Upvotes: 2

Related Questions