如何将字符串向量转换为数据框或矩阵

时间:2012-10-26 00:58:00

标签: r

我有一个n长度数字的向量,看起来像这样(在这种情况下,n = 3):

[1] "111" "111" "111" "111" "111" "111" "111" "111" "111" "111" "111" "111"
[13] "111" "111" "111" "111" "111" "111" "111" "111" "111" "111" "111" "111"
[25] "111" "111" "111" "111" "111" "111" "111" "1 1" "111" "  1" "111" "112"
[37] "121" "111" "111" "111" "11 " "111" "   " "111" "111" "221" "111" "111"
[49] "   " "111" "111"

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

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。

2 个答案:

答案 0 :(得分:9)

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

y <- strsplit(x,"")
z <- lapply(y, as.numeric)
a <- do.call(rbind, z)

这比上述解决方案更快,但不太直观。 sapply简化为数组,但您必须转置它,因为维度与您想要的相反。

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

答案 1 :(得分:6)

以下是使用read.fwf()的解决方案。

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