Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.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,我有一个由n个长度的数字串组成的向量,看起来像这样(在本例中,n=3): 我想将其转换为如下所示的矩阵(或数据帧): V1 V2 V3 1 1 1 1 1 1 1 1 1 ... 1 NA 1 1 1 1 NA NA 1 等等 我知道我可以用substring()和as.numeric()在双嵌套循环中实现,但必须有一种更像R的方法来实现这一点。有人能提供线索吗 TIA。您可以使用strsplit。例如(假设向量是名为x

我有一个由n个长度的数字串组成的向量,看起来像这样(在本例中,n=3):

我想将其转换为如下所示的矩阵(或数据帧):

V1   V2   V3
1    1    1
1    1    1
1    1    1
...
1   NA    1
1    1    1
NA   NA   1
等等

我知道我可以用substring()和as.numeric()在双嵌套循环中实现,但必须有一种更像R的方法来实现这一点。有人能提供线索吗


TIA。

您可以使用
strsplit
。例如(假设向量是名为
x
的对象):

以下是答案中提出的不同方法的时间比较(到目前为止):


x这里有一个使用
read.fwf()
的解决方案


x我想再澄清一下会有帮助的。我不清楚你是如何从a跳到b的。也请提供一个可重复的例子。@JoshuaUlrich——我想你可能会喜欢。不过,你的速度更快,伸缩性更好,所以这只是一个好奇。(I
system.time()
'd和
x
V1   V2   V3
1    1    1
1    1    1
1    1    1
...
1   NA    1
1    1    1
NA   NA   1
y <- strsplit(x,"")
z <- lapply(y, as.numeric)
a <- do.call(rbind, z)
a <- t(sapply(y, as.numeric))
x <- sample(c("111","1 1","  1","112","121","11 ","   ","221"), 1e5, TRUE)
f1 <- function(x) do.call(rbind, lapply(strsplit(x,""), as.numeric))
f2 <- function(x) t(sapply(strsplit(x,""), as.numeric))
f3 <- function(x) read.fwf(file=textConnection(x), widths=c(1,1,1))
library(rbenchmark)
benchmark(f1(x), f2(x), f3(x), replications=10, order="relative",
  columns=c("test","replications","elapsed","relative"))
#    test replications elapsed  relative
# 2 f2(x)           10   5.072  1.000000
# 1 f1(x)           10   6.343  1.250591
# 3 f3(x)           10 119.892 23.638013
x <- c("111", "   ", "221", "  1")

## "fwf" stands for "*f*ixed *w*idth *f*ormatted"
read.fwf(file = textConnection(x), widths = c(1,1,1))
#   V1 V2 V3
# 1  1  1  1
# 2 NA NA NA
# 3  2  2  1
# 4 NA NA  1