Convert a character variable to a list of list

前端 未结 2 856
广开言路
广开言路 2020-12-12 03:32

i want to convert a character variable to a list of list. My character looks like as follows:

\"[[\"a\",2],[\"b\",5]]\"

The expected list

相关标签:
2条回答
  • 2020-12-12 04:15

    Looks like a JSON list to me, which will make your parsing job pretty simple:

    x <- '[["a",2],["b",5]]'
    
    library(jsonlite)
    fromJSON(x, simplifyVector=FALSE)
    #[[1]]
    #[[1]][[1]]
    #[1] "a"
    #
    #[[1]][[2]]
    #[1] 2
    #
    #
    #[[2]]
    #[[2]][[1]]
    #[1] "b"
    #
    #[[2]][[2]]
    #[1] 5
    

    If you want it combined back to columns instead, just let the simplification occur by default:

    fromJSON(x)
    #     [,1] [,2]
    #[1,] "a"  "2" 
    #[2,] "b"  "5" 
    
    0 讨论(0)
  • 2020-12-12 04:18

    Here is one possibility via base R,

    xx <- '[[a, 2], [b, 5]]'
    lapply(split(matrix(gsub('[[:punct:]]', '', unlist(strsplit(xx, ','))), 
                                                 nrow = 2, byrow = T), 1:2), 
                                                 function(i) list(i[[1]], as.numeric(i[[2]])))
    
    #$`1`
    #$`1`[[1]]
    #[1] "a"
    
    #$`1`[[2]]
    #[1] 2
    
    
    #$`2`
    #$`2`[[1]]
    #[1] " b"
    
    #$`2`[[2]]
    #[1] 5
    
    0 讨论(0)
提交回复
热议问题