6

我有一个长度为 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。

4

2 回答 2

12

您可以使用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
于 2012-10-26T01:02:57.880 回答
7

这是一个使用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
于 2012-10-26T02:30:44.710 回答