gpt4 book ai didi

r - 从strsplit列表中提取向量,而无需使用循环

转载 作者:行者123 更新时间:2023-12-03 15:13:55 26 4
gpt4 key购买 nike

考虑以下 vector :

[1] "1-1694429" "2-1546669" "3-928598"  "4-834486"  "5-802353"  "6-659439"  "7-552850" 
"8-516804" "9-364061"
[10] "10-354181" "11-335154" "12-257915" "13-251310" "14-232313" "15-217628" "16-216569"

我正在尝试生成两个 vector ,每个 vector 都包含通过用定界符“-”分割 vector 的每个元素而获得的值。

我用了:
f <- function(s) strsplit(s, "-")
cc<-sapply(names.reads, f)

head(cc) $1-1694429 [1] "1" "1694429"


$`2-1546669`

[1] "2" "1546669"

我知道我可以像这样访问它们:
> cc[[1]][1]
[1] "1"

> cc[[1]][2]
[1] "1694429"

我想有两个 vector ,每个 vector 包含存储在 cc[[i]][1]cc[[i]][2]中的值...我可以不使用循环来做到这一点吗? (我有超过一百万个元素)

最佳答案

使用math.coffee的建议,以下代码避免循环或sapply

names.reads <- c("1-1694429", "2-1546669", "3-928598", "4-834486", "5-802353",
"6-659439", "7-552850", "8-516804", "9-364061", "10-354181",
"11-335154", "12-257915", "13-251310", "14-232313", "15-217628",
"16-216569")

cc <- strsplit(names.reads,'-')
part1 <- unlist(cc)[2*(1:length(names.reads))-1]
part2 <- unlist(cc)[2*(1:length(names.reads)) ]

产生
> part1
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15"
[16] "16"
> part2
[1] "1694429" "1546669" "928598" "834486" "802353" "659439" "552850"
[8] "516804" "364061" "354181" "335154" "257915" "251310" "232313"
[15] "217628" "216569"

尽管它确实要求每个原始值都应采用预期的格式。

关于r - 从strsplit列表中提取向量,而无需使用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8996134/

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