Convert a character variable to a list of list

前端 未结 2 814
广开言路
广开言路 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: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
    

提交回复
热议问题