Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"[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]

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading