Prevent unlist to drop NULL values

前端 未结 4 681
梦毁少年i
梦毁少年i 2020-12-04 16:19

I have a vector of lists and I use unlist on them. Some of the elements in the vectors are NULL and unlist seems to be dropping them.<

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 17:00

    The issue here is that you can't have NULL in the middle of a vector. For example:

    > c(1,NULL,3)
    [1] 1 3
    

    You can have NA in the middle though. You could could convert it to character and then back to numeric, which automatically converts the NULL values to NA (with a warning):

    > b <- as.numeric(as.character(a))
    Warning message:
    NAs introduced by coercion 
    

    then put the names back in, because they've been dropped by the previous operation:

    > names(b) <- names(a)
    > b
    p1 p2 p1 p2 p1 p2 p1 p2 
    2  5  3  4 NA NA  4  5 `
    

提交回复
热议问题