我收到一个字符串,这是一个数字列表:
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
数字?
我尝试过使用strsplit
,as.data.frame
,但似乎很长。
我想要一些高效和富有创意的东西。
答案 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_extract
(stringi
包)从字符串中提取数字。 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"
然后将vector
个character
元素转换为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