Home > Mobile >  How to convert char (e.g., "[1, 2, 3]" ) to a list (e.g., [1, 2, 3])
How to convert char (e.g., "[1, 2, 3]" ) to a list (e.g., [1, 2, 3])

Time:04-13

Is there a nice way to convert a column of chars in a dataframe to a list in R Studio?

e.g.

convert type chr

"[1, 2, 3]"
"[11, 24, 3]"
"[1, 21, 3]"
"[14, 2, 31]"

to list

[1, 2, 3]
[11, 24, 3]
[1, 21, 3]
[14, 2, 31]

CodePudding user response:

Those are not lists in R; they look like lists in python (language) and json (structure). We can capitalize on the latter:

vec <- c("[1, 2, 3]", "[11, 24, 3]", "[1, 21, 3]", "[14, 2, 31]")
jsonlite::stream_in(textConnection(paste(vec, collapse = "\n")), 
                    simplifyDataFrame = FALSE, simplifyMatrix = FALSE)
#  Imported 4 records. Simplifying...
# [[1]]
# [1] 1 2 3
# [[2]]
# [1] 11 24  3
# [[3]]
# [1]  1 21  3
# [[4]]
# [1] 14  2 31

CodePudding user response:

What about gsub str2lang eval?

> s <- c("[1, 2, 3]", "[11, 24, 3]", "[1, 21, 3]", "[14, 2, 31]")

> lapply(gsub("\\[(.*)\\]", "c(\\1)", s), function(x) eval(str2lang(x)))
[[1]]
[1] 1 2 3

[[2]]
[1] 11 24  3

[[3]]
[1]  1 21  3

[[4]]
[1] 14  2 31

Another option is using py_eval from reticulate package

> library(reticulate)

> lapply(s, py_eval)
[[1]]
[1] 1 2 3

[[2]]
[1] 11 24  3

[[3]]
[1]  1 21  3

[[4]]
[1] 14  2 31
  • Related