在R中将多元素字符转换为不同的独立元素

在R中将多元素字符转换为不同的独立元素,r,dataframe,R,Dataframe,我需要帮助将一个字符从几个元素转换为独立元素 例如: 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" cad我们可以使用scanfrombase R基本上将元素提取成向量,并可以包装成数据。frame data.frame(cad = scan(text = cad, what = numeric())) # cad #1 0 #2 1 #3 2 #4 3

我需要帮助将一个字符从几个元素转换为独立元素

例如:

 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"

cad我们可以使用
scan
from
base R
基本上将元素提取成
向量
,并可以包装成
数据。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
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

或者另一个选项是
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
(也可以处理多个字符串)


我们可以使用
scan
from
base R
,它基本上将元素提取到
向量中,并可以包装到
数据中。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
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

或者另一个选项是
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
(也可以处理多个字符串)


我们可以使用
strsplit
在空白处拆分文本,并将其包装在
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
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

我们可以使用
strsplit
在空白处拆分文本,并将其包装在
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
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