Reputation: 326
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 should contain two lists with a character and a number for each
Upvotes: 1
Views: 144
Reputation: 93803
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"
Upvotes: 1
Reputation: 51582
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
Upvotes: 1