Someone just posted some console output as an example. (This happens a lot, and I have strategies for converting output of print for vectors and dataframes.) I'm wondering if anyone has an elegant method for parsing this to a real R list?
test <- "[[1]]
[1] 1.0000 1.9643 4.5957
[[2]]
[1] 1.0000 2.2753 3.8589
[[3]]
[1] 1.0000 2.9781 4.5651
[[4]]
[1] 1.0000 2.9320 3.5519
[[5]]
[1] 1.0000 3.5772 2.8560
[[6]]
[1] 1.0000 4.0150 3.1937
[[7]]
[1] 1.0000 3.3814 3.4291"
This is an example with named and un-named nodes:
L <-
structure(list(a = structure(list(d = 1:2, j = 5:6, o = structure(list(
w = 2, 4), .Names = c("w", ""))), .Names = c("d", "j", "o"
)), b = "c", c = 3:4), .Names = c("a", "b", "c"))
> L
$a
$a$d
[1] 1 2
$a$j
[1] 5 6
$a$o
$a$o$w
[1] 2
$a$o[[2]]
[1] 4
$b
[1] "c"
$c
[1] 3 4
I've worked through the code of how str
handles lists, but it's doing essentially the inverse transformation. I figure that this needs to be structured somewhat along these lines where there will be a recursive call to something like this logic, since lists can be named (in which there will be "$" preceding the last index) or unnamed(in which case there will be a number enclosed in "[[.]]".
parseTxt <- function(Lobj) {
#setup logic
# Untested code... basically a structure to be filled in
rdLn <- function(Ln) {
for( ln in length(inp) ) {
m <- gregexpr("\\[\\[|\\$", "$a$o[[2]]")
separators <- regmatches("$a$o[[2]]", m)
curr.nm=NA
if ( tail( separators, 1 ) == "$" ){
nm <- sub("^.+\\$","",ln)
if( !nm %in% curr.nm){ curr.nm <-c(nm, curr.nm) }
} else { if (tail( separators, 1 ) == '[[' ){
# here need to handle "[[n]]" case
} else { and here handle the "[n]" case
}
}
}
I wouldn't call it "elegant", but for unnamed lists you could do some checking/modifications to something along these lines:
Of course, this is specific to lists only and this particular example is specifically
what = double()
, so that would require additional checking. An idea that pops into my head to detect character elements in the list would be to make thewhat
argumentHere's my shot at a solution. It works well on both your test cases, and on the few others with which I've tested it.
With
L
, your more complicated example list, here's what it gives:And here's how it handles the print representation of
test
, your more regular list:One more example: