Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中拆分字符串_R - Fatal编程技术网

在R中拆分字符串

在R中拆分字符串,r,R,考虑: x<-strsplit("This is an example",split="\\s",fixed=FALSE) 像这样,x[3]是空的。但如果我没有列出,那么: > x<-unlist(x) > x [1] "This" "is" "an" "example" > length(x) [1] 4 >x [1] 这是一个“示例” >长度(x) [1] 4 只是现在x[3]是“an” 为什么列表最初不是按长度4排列的,这样

考虑:

x<-strsplit("This is an example",split="\\s",fixed=FALSE)
像这样,x[3]是空的。但如果我没有列出,那么:

> x<-unlist(x)
> x
[1] "This"    "is"      "an"      "example"
> length(x)
[1] 4 
>x
[1] 这是一个“示例”
>长度(x)
[1] 4 
只是现在x[3]是“an”


为什么列表最初不是按长度4排列的,这样就可以通过索引访问元素了?这给访问拆分的元素带来了麻烦,因为我必须首先取消列表

这允许为其输入参数对
strsplit
进行矢量化。例如,它将允许您拆分向量,例如:

x <- c("string one", "string two", "and string three")

这是因为
strsplit
生成一个包含每个元素(单词)的列表。 试一试


因为,如
?strsplit
中所述,返回的值是:“与x长度相同的列表,其第i个元素包含x[i]的拆分向量”。您给它一个长度为1的向量,因此您得到了长度为1的列表,其第一个元素包含拆分向量。您仍然可以通过
x[[1]][3]
x <- c("string one", "string two", "and string three")
> x <- c("string one", "string two", "and string three")
> y  <- strsplit(x, "\\s")
> y[[2]][2]
[1] "two"
> x[[1]]
#[1] "This"    "is"      "an"      "example"
> length(x[[1]])
#[1] 4