给定一个列表作为字符串,如何转换回数字列表?

时间:2018-04-02 06:11:57

标签: r string list type-conversion

我收到一个字符串,这是一个数字列表:

s <- "[14,7,5,3,4,0,1,7,2,3,1,18,13,4,23,7,8,8,11,18,15,6,2,10,2,4,8,5,11,5,1,5,2,4,3,1,6,8,5,5,3,1,1,4,5,2,9,3,4,11,11,14,3,12,2,6,0,0,15,1,18,5,3,6,6,6]"

请指导我如何将其转换回常规的list数字? 我尝试过使用strsplitas.data.frame,但似乎很长。 我想要一些高效和富有创意的东西。

3 个答案:

答案 0 :(得分:3)

1)JSON 问题中显示的输入是JSON格式,因此请使用jsonlite或rjson包,它将为您执行所需的字符串处理。

library(jsonlite)
fromJSON(s)

,并提供:

 [1] 14  7  5  3  4  0  1  7  2  3  1 18 13  4 23  7  8  8 11 18 15  6  2 10  2
[26]  4  8  5 11  5  1  5  2  4  3  1  6  8  5  5  3  1  1  4  5  2  9  3  4 11
[51] 11 14  3 12  2  6  0  0 15  1 18  5  3  6  6  6

2)strapply 如果你确实想要使用字符串处理,那么一个选项是strapply提取所有数字序列"\\d+"并转换为数字给出相同的输出如上所述。

library(gsubfn)
strapply(s, "\\d+", as.numeric, simplify = c)

3)扫描或没有任何包或正则表达式:

scan(text = chartr("[]", "  ", s), sep = ",", quiet = TRUE)

答案 1 :(得分:1)

一种选择是使用stri_extractstringi包)从字符串中提取数字。 stri_extract_all的输出为list vector length 1。通常情况下,如果有多个元素的&#39} (此处为单个字符串),要将其转换为单个vector,我们使用unlist然后使用as.integer换行。由于只有一个list元素,我们可以使用[[

提取该元素
library(stringi)
as.integer(stri_extract_all(s, regex = "\\d+")[[1]])

如果我们拆分代码,如上所述,stri_extract_all会返回长度为1的list

stri_extract_all(s, regex = "\\d+")
#[[1]]####
#[1] "14" "7"  "5"  "3"  "4"  "0"  "1"  "7"  "2"  "3"  "1"  "18" "13" "4"  "23" "7"  "8"  "8"  "11" "18" "15" "6"  "2"  "10"
#[25] "2"  "4"  "8"  "5"  "11" "5"  "1"  "5"  "2"  "4"  "3"  "1"  "6"  "8"  "5"  "5"  "3"  "1"  "1"  "4"  "5"  "2"  "9"  "3" 
#[49] "4"  "11" "11" "14" "3"  "12" "2"  "6"  "0"  "0"  "15" "1"  "18" "5"  "3"  "6"  "6"  "6" 

提取包含list

vector元素
stri_extract_all(s, regex = "\\d+")[[1]]
#[1] "14" "7"  "5"  "3"  "4"  "0"  "1"  "7"  "2"  "3"  "1"  "18" "13" "4"  "23" "7"  "8"  "8"  "11" "18" "15" "6"  "2"  "10"
#[25] "2"  "4"  "8"  "5"  "11" "5"  "1"  "5"  "2"  "4"  "3"  "1"  "6"  "8"  "5"  "5"  "3"  "1"  "1"  "4"  "5"  "2"  "9"  "3" 
#[49] "4"  "11" "11" "14" "3"  "12" "2"  "6"  "0"  "0"  "15" "1"  "18" "5"  "3"  "6"  "6"  "6" 

然后将vectorcharacter元素转换为integer

答案 2 :(得分:1)

这里是R基础解决方案

此行仅提取数字并将其保存到列表中。

numbers <- regmatches(s, gregexpr("[[:digit:]]+", s))

取消列表并将其转换为数字。

numbers <- as.numeric(unlist(numbers))

<强>结果

 [1] 14  7  5  3  4  0  1  7  2  3  1 18 13  4 23  7  8  8 11 18 15  6  2 10  2  4  8  5 11  5  1  5  2  4
[35]  3  1  6  8  5  5  3  1  1  4  5  2  9  3  4 11 11 14  3 12  2  6  0  0 15  1 18  5  3  6  6  6