简体   繁体   中英

How to convert the result of lapply with NA items to a data frame in R?

I have a list as a result of an lapply where the function is covered with a trycatch function because I have a super long list that I need my code to go through without being stopped by any error. The result looks like this: 在此处输入图片说明

I tried using

test12 <- data.frame(matrix(unlist(y), nrow=length(y), byrow = T))

However, the data frame looks very strange and it's not really in the order I wanted. It looks like the NA [[20]] has created a break in the data frame. Anyone has experience on how to convert this list into a data frame? The expected columns are: Title , Description , and Keywords , and is it possible to have those NA like item [[20]] as NA value in all 3 columns? Thank you.

With base R we can do

do.call(rbind.data.frame, y)

#           Title Description Keywords
#2  Tetris Layout          NA       NA
#21 Tetris Layout          NA       NA
#3           <NA>          NA       NA
#4  Tetris Layout          NA       NA

data

y <- list(list(Title = "Tetris Layout", Description = NA, Keywords= NA), 
          list(Title = "Tetris Layout", Description = NA, Keywords= NA), 
          NA, 
          list(Title = "Tetris Layout", Description = NA, Keywords= NA))

Another option with tidyverse

library(tidyverse)
map_df(liste,  as_tibble) %>%
          select(1:3)
# A tibble: 4 x 3
#  Title Description Keyword
#  <chr> <chr>       <chr>  
#1 xxx   xxx2        xxx3   
#2 yyy   yyy2        yyy3   
#3 <NA>  <NA>        <NA>   
#4 zzz   zzz2        zzz3   

data

liste  <- list(list("Title" = "xxx", "Description" = "xxx2", "Keyword" = "xxx3"),
             list("Title" = "yyy", "Description" = "yyy2", "Keyword" = "yyy3"),
             NA,
             list("Title" = "zzz", "Description" = "zzz2", "Keyword" = "zzz3"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM