Chargaff
Chargaff

Reputation: 1572

How to create and populate lists from a table object in R

How to create a list from this table :

t1 <- structure(c(1L, 2L, 3L), .Dim = 3L, .Dimnames = structure(list(c("a", "b", "c")), .Names = ""), class = "table")

so to get one list for every "name" of the table, and each list would be the length of the appropriate "name" ? Expected output would be :

> result
$a
[1] NA
$b
[1] NA NA
$c
[1] NA NA NA

I would have thought that an lapply call would do the trick :

lapply(t1,function(x) list(names(x)=NA,length(x)))

But it obviously doesn't work. Any ideas ?

Upvotes: 1

Views: 164

Answers (2)

CHP
CHP

Reputation: 17189

t1
## 
## a b c 
## 1 2 3 

lapply(t1, function(x) rep(NA, x))
## $a
## [1] NA
## 
## $b
## [1] NA NA
## 
## $c
## [1] NA NA NA
## 

Upvotes: 2

juba
juba

Reputation: 49053

You can do something like this :

R> lapply(as.list(t1), function(v) {return(rep(NA,v))})
$a
[1] NA
$b
[1] NA NA
$c
[1] NA NA NA

Upvotes: 1

Related Questions