Reputation: 5580
I have a strange R list, in which odd list elements that are strings should be names of even list elements. Some elements are lists inside the lists. The depth of the list is not predefined in advance. And the simplified structure of the list is approximately:
a <- list("key0",
"value0",
"key",
list("key1", "value1",
"key2", "value2",
"key3", list("key6", "value6"),
"key4", "value4",
"key5", list(list(list("key7", "value7")))
))
How from list a
can I get a regular named R list b
?
b <- list(key0 = "value0",
key = list(key1 = "value1",
key2 = "value2",
key3 = list(key6 = "value6"),
key4 = "value4",
key5 = list(list(list(key7 = "value7")))
))
Does list a
like data structure have any special technical name?
Upvotes: 1
Views: 337
Reputation: 47320
Using a recursive function :
fun <- function(x){
x <- lapply(x,function(y) if (is.list(y)) y <- fun(y) else y)
if(!is.null(names(x)) | length(x) == 1) return(x)
x <- setNames(x[seq_along(x)%%2 == 0], x[seq_along(x)%%2 == 1])
x
}
res <- fun(a)
identical(b,res)
# [1] TRUE
Upvotes: 4