Home > front end >  Convert lists to data frame with NULL values
Convert lists to data frame with NULL values

Time:05-05

For the below lists, can we convert to dataframe

x1 <- list(a1 = structure(19116, class = "Date"), inputType = TRUE, 
           valDate = structure(19116, class = "Date"), MainNavBar = "V", 
           btnGetDWData = structure(0L, class = c("integer", "shinyActionButtonValue"
           )), sd = "Info", fd = NULL, 
           fd = NULL)

I tried with below, but I am getting error. Can anyone help me?

> data.frame(
   names = names(x1),
      values = unlist(x1, use.names = FALSE)
  )
Error in data.frame(names = names(x1), values = unlist(x1, use.names = FALSE)) : 
  arguments imply differing number of rows: 8, 6

CodePudding user response:

Sotos answer is perfect.

Another approach, because I work a lot with nested data:

library(dplyr)
library(tidyr)
library(purrr)

tibble(
  key = names(x1),
  data = x1
) %>% 
  mutate(data = map(data, as.character)) %>% 
  unnest(data)

Output is:

# A tibble: 6 × 2
  key          data      
  <chr>        <chr>     
1 a1           2022-05-04
2 inputType    TRUE      
3 valDate      2022-05-04
4 MainNavBar   V         
5 btnGetDWData 0         
6 sd           Info 

CodePudding user response:

Replace the NULL with NA and bind, i.e.

do.call(cbind.data.frame, lapply(x1, function(i)replace(i, length(i) == 0, NA)))

          a1 inputType    valDate MainNavBar btnGetDWData   sd fd fd
1 2022-05-04      TRUE 2022-05-04          V            0 Info NA NA

There are a lot of ways to add another column. To keep it a one-liner, here is an idea,

transform(do.call(cbind.data.frame, lapply(x1, function(i)replace(i, length(i) == 0, NA))), time = Sys.time())

          a1 inputType    valDate MainNavBar btnGetDWData   sd fd fd.1                time
1 2022-05-04      TRUE 2022-05-04          V            0 Info NA   NA 2022-05-05 10:46:11

CodePudding user response:

Your issue is that you have list of elements with NULL value. Once this problem is resolved (replaced with NA), you can use data.frame:

data.frame(lapply(x1, \(x) ifelse(is.null(x), NA, x)), a = "a")

     a1 inputType valDate MainNavBar btnGetDWData   sd fd fd.1 a
1 19116      TRUE   19116          V            0 Info NA   NA a
  •  Tags:  
  • r
  • Related