在将字符从多个元素转换为独立元素时,我需要帮助。
示例:
cad <- c("0 1 2 3 4 5 6 7 8 9 10 11")
cad
[1] "0 1 2 3 4 5 6 7 8 9 10 11"
到
a <- 0:11
data.frame(a)
cad
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
10 9
11 10
12 11
谢谢
答案 0 :(得分:0)
我们可以使用scan
中的base R
,基本上将元素提取到vector
中并可以包装到data.frame
data.frame(cad = scan(text = cad, what = numeric()))
# cad
#1 0
#2 1
#3 2
#4 3
#5 4
#6 5
#7 6
#8 7
#9 8
#10 9
#11 10
#12 11
或者另一个选择是read.table
read.table(text = gsub(" ", "\n", cad), header = FALSE, col.names = 'cad')
# cad
#1 0
#2 1
#3 2
#4 3
#5 4
#6 5
#7 6
#8 7
#9 8
#10 9
#11 10
#12 11
或者另一个选择是将strsplit
与unlist
(也将处理多个字符串)
data.frame(cad = unlist(strsplit(cad, "\\s+")))
答案 1 :(得分:0)
我们可以使用strsplit
在空白处分割文本并将其包装在data.frame
data.frame(cad = strsplit(cad, "\\s+")[[1]])
# cad
#1 0
#2 1
#3 2
#4 3
#5 4
#6 5
#7 6
#8 7
#9 8
#10 9
#11 10
#12 11