Convert console output of list to a real R list

前端 未结 2 903
一个人的身影
一个人的身影 2021-02-08 03:44

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 a

2条回答
  •  离开以前
    2021-02-08 04:21

    I wouldn't call it "elegant", but for unnamed lists you could do some checking/modifications to something along these lines:

    s <- strsplit(gsub("\\[+\\d+\\]+", "", test), "\n+")[[1]][-1]
    lapply(s, function(x) scan(text = x, what = double(), quiet = TRUE))
    
    [[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
    

    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 the what argument

    what = if(length(grep("\"", x))) character() else double()
    

提交回复
热议问题