I want to store non-rectangular data in a structure, e.g. in a list
.
Referencing previous data works using a tibble
, e.g. like this:
dat <- tibble(a = 2,
b = list(c(a 1, a 2)),
c = list(tibble(a = a, b = 3)))
Note that because tibble
does not allow tibble
in columns (otherwise the data would not be rectangular), we have to wrap the tibble
in a list and dat$c
does not return the tibble
, for that we need dat$c[[1]]
.
The latter problem can be solved with a list
.
dat2 <- list(a = 2,
b = c(3, 4),
c = tibble(a = 2, b = 3))
However, now I can't construct the data element with reference to previous entries:
dat2 <- list(a = 2,
b = c(a 1, a 2),
c = tibble(a = a, b = 3))
> Error: object 'a' not found
My question: Is there a way to construct a non-rectangular data structure that does support construction by reference to previous entries?
CodePudding user response:
You can use lst()
instead:
lst(a = 2,
b = c(a 1, a 2),
c = tibble(a = a, b = 3))
$a
[1] 2
$b
[1] 3 4
$c
# A tibble: 1 × 2
a b
<dbl> <dbl>
1 2 3
CodePudding user response:
You can use a = (a <- 2)
for the reference
dat <- tibble(
a = (a<-2),
b = list(c(a 1, a 2)),
c = list(tibble(a = a, b = 3))
)
and you will see
> str(dat)
tibble [1 x 3] (S3: tbl_df/tbl/data.frame)
$ a: num 2
$ b:List of 1
..$ : num [1:2] 3 4
$ c:List of 1
..$ : tibble [1 x 2] (S3: tbl_df/tbl/data.frame)
.. ..$ a: num 2
.. ..$ b: num 3