dimanche 23 octobre 2016

R: elements as NULL get dropped when combined to list

I am trying to using for loop to obtain six elements from a nested list of data frames, then put these elements together into a list length of six. Then rbind list into a data frame with six columns. I found that every time when the element is NULL, it will be automatically dropped, before it gets into the list.

Below is a truncated version of the code. Sorry the data itself has too many levels of lists and I don't know how to paste a good piece of it here.

    ob_dat<-data.frame(a=character(0), b=character(0), c=character(0), d=character(0),e=character(0), f=character(0), stringsAsFactors=FALSE)
    e<-e_previous
    f<-f_previous
    for (k in 1:nrow(dat)){
    a<-dat$id[[k]]
    b<-dat$subject[[k]]
    c<-dat$updated[[k]]
    d<-dat$type[[k]]
    ob_list<-as.list(c(a,b,c,d,e,f))
    ob_list<-lapply(ob_list, function(x) ifelse(x == "NULL", NA, x))
ob_dat<rbind(ob_dat,setNames(ob_list,names(ob_dat)))        
    ob_dat[,1:6]<-apply(ob_dat[,1:6],2,as.character)   
  }

The code ran well for all records that didn't have NULL, until once some of the elements, say, c and d are NULL. It gave me the error like below:

Error in setNames(ob_list, names(ob_dat)) : 

'names' attribute [6] must be the same length as the vector [4]

Apparently, the NULL elements of c and d were dropped before even join the other elements into the list ob_list. I tried to use something like:

c<-ifelse(c=="NULL",NA,c). I was hoping that using `ifelse` can change all `NULL` to `NA`. However, c was changed into `logical(0)` when c was NULL. 

Please help. Thanks.

Aucun commentaire:

Enregistrer un commentaire