1

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
0

3 Answers 3

4

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 
Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

perfect, you also account for the NULL data. Ty, a lot learned ;)
One question. Can we add another column at he last called Time. So basicallly, it shold take Sys.time()
0

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

2 Comments

Is there something wrong with this answer?
Can be more compact data.frame(replace(x1, lengths(x1)== 0, NA), a = "a"). Also, if there is a NULL element in the list, one of the conditions in ifelse will not be met i.e. all the arguments should have same length

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.