gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:11:52 24 4
gpt4 key购买 nike

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

最佳答案

您可以使用 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

关于r - 如何将字符串向量转换为数据框或矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13079431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com