如何将 char(例如,“[1, 2, 3]”)转换为列表(例如,[1, 2, 3])

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

有没有一种很好的方法可以将数据框中的一列字符转换为 R Studio 中的列表?

例如

转换类型 chr

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

列出

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

那些不是R中的列表;它们看起来像 python(语言)和 json(结构)中的列表。我们可以利用后者:

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

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

另一个选项是使用 reticulate 包中的 py_eval

> 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

这里是使用 strsplit.

的方法
strsplit(x, '\D+') |> lapply(`[`, -1)
# [[1]]
# [1] "1" "2" "3"
# 
# [[2]]
# [1] "11" "24" "3" 
# 
# [[3]]
# [1] "1"  "21" "3" 
# 
# [[4]]
# [1] "14" "2"  "31"

数据:

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