How do I create a data.frame using c() (nested?) as column values?

Seems like a really simple question, but I'm all out of trying different ways and searching. Here are few of the ways I tried:

data.frame(a = c(list('a','b'),
                 list('b'))) |> 
  bind_rows(data.frame(a = list('c')))

data.frame(a = c(c('a','b'),
                 'b')) |> 
  bind_rows(data.frame(a = c('c')))

tidytable(a = c(list('a','b'),
                 list('b'))) |> 
  bind_rows(tidytable(a = list('c')))

tidytable(a = c(c('a','b'),
                 'b')) |> 
  tidytable(data.frame(a = c('c')))

The actual data doesn't matter, but I would like the output to be something like this:

COLUMN1                  
<chr>                         
"c(\"a\", \"b\")"       
"character(0)"                
"z"   
"c(\"y\", \"z\")"

I can't seem to make it behave the way I want it to. This is all so that I can create a reprex (after).

It's unclear what this is intended to do, because coerces its argument to a data.table object. Although data.table-tweeked data.frame objects have very desirable features, mixing {dplyr} syntax into the mix will at best lead to confusion.

It's unclear whether you want to derive this from some other data, so I'll just give a ways to enter it direct.

y <- data.frame(COLUMN1 = as.character(rep(NA,4)))
y[1,] <- "c(\"a\", \"b\")"
y[2,1] <- '\"character(0)\"'
y[3,1] <- '\"z\"'
y[4,] <- "c(\"y\", \"z\")"
y
#>          COLUMN1
#> 1    c("a", "b")
#> 2 "character(0)"
#> 3            "z"
#> 4    c("y", "z")
str(y)
#> 'data.frame':    4 obs. of  1 variable:
#>  $ COLUMN1: chr  "c(\"a\", \"b\")" "\"character(0)\"" "\"z\"" "c(\"y\", \"z\")"

Created on 2023-11-26 with reprex v2.0.2

You ultimate intent isn't clear. Is this in aid of meta-programming?

1 Like

you can not have such a column with a chr type, you must have a column with a list type if an entry in such a list may need to be a chr vector with length > 1. Also a vanilla data.frame wouldnt support this direct construction, but a tibble would. A tibble of this kind will as.data.frame into a functioning data.frame so its just a matter of what one can do when manually constucting data.frames vs tibbles.

library(tidyverse)

example <- tibble(a = list(c('a','b'),
                           character(0),
                           "z",
                           c('y','z')))

example
str(example)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.