Reputation: 145
The function relist()
(by default) doesn't re-list when the list was not flatten recursively . For example
> my_list=list(a=list(aa=c(1,2),ab=2),b=list(ba=1,bb=2))
> flat=unlist(as.relistable(my_list),recursive=FALSE)
Warning message:
In unlist.relistable(x, recursive, use.names) :
relist() requires recursively unlisted objects.
>relist(flat)
$a
$a$aa
$a$aa[[1]]
[1] 1 2
$a$aa[[2]]
[1] 2
$a$ab
$a$ab[[1]]
[1] 1
$b
$b$ba
$b$ba[[1]]
[1] 2
$b$bb
$b$bb[[1]]
NULL
I came up with a partial answer and seems to work, but is there a better and complete way to do it?
Upvotes: 1
Views: 172
Reputation: 39647
With your not recursive unlisted list you can make again an unlist
and use the stored skeleton for relist
.
relist(unlist(flat), attr(flat,"skeleton"))
#$a
#$a$aa
#[1] 1 2
#
#$a$ab
#[1] 2
#
#
#$b
#$b$ba
#[1] 1
#
#$b$bb
#[1] 2
#
#
#attr(,"class")
#[1] "relistable" "list"
Upvotes: 1
Reputation: 145
This seems to work and handles a recursive output of unlist()
that is not fully recursive (didn't break arrays or matrices)
my_relist <- function(x){
y=list()
x=as.list(x)
for (name in names(x)){
split=strsplit(name,'.',fixed=TRUE)[[1]]
char='y'
for (str in split){
char=paste(char,'$',str,sep="")
}
char=paste(char,'= x[[name]]',sep="")
eval(parse(text=char))
}
return(y)
}
Upvotes: 0