gpt4 book ai didi

r - 串联成组的矢量元素

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

list1 转换为 list2,以及将 list2 转换为 list1 的最优雅方法是什么?

list1<- c('a','b','c','d','e','f','g','h','i')
list2<- c('abc','def','ghi')

即:接触三个一组的元素。

谢谢:D

最佳答案

list1 <- letters[1:10] (展示当向量的长度不是 3 的倍数时它是如何工作的)。然后,试试这个:

list1 到 list2

# method 1 (seems to be the fastest so far, 
# my suspicions about loop being slower were wrong)
list2 <- sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = "")
# alternatively as @flodel mentions
list2 <- tapply(list1, (seq_along(list1)-1) %/% 3, paste, collapse = "")

tapply版本运行时间与 sapply+split 相似(基准测试未显示)。

更进一步,使用@JoshOBrien 在 this post 中的想法

# method 2
pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]])"
strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
# [1] "abc" "def" "ghi" "j"

如果你想把最后一部分连接到最后一个(这里是 jghi ),那么,做:

pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]]{3})"
strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
# [1] "abc" "def" "ghij"

list2 到 list1

unlist(strsplit(list2, ""), use.names=FALSE)
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

这是 method1 的基准测试, method2和埃迪的:

数据:

list1 <- sample(letters, 1e5, replace=TRUE)

功能:

arun <- function() {
pattern <- "(?<=[[:alnum:]]{3})(?=[[:alnum:]])"
strsplit(paste(list1, collapse=""), pattern, perl=TRUE)[[1]]
}

arun2 <- function() {
unname(sapply(split(list1, (seq_along(list1)-1) %/% 3), paste, collapse = ""))
}

eddi <- function() {
substring(paste(list1, collapse = ""),
seq(1, length(list1), 3),
pmin(seq(3, length(list1)+2, 3), length(list1)))
}

基准测试:

require(microbenchmark)
microbenchmark(t1 <- arun(), t2 <- eddi(), t3 <- arun2(), times=10)
identical(t1, t2) # TRUE
identical(t1, t3) # TRUE

# Unit: milliseconds
# expr min lq median uq max neval
# t1 <- arun() 3352.9867 3400.8627 3512.7037 3585.6499 3635.2182 10
# t2 <- eddi() 3302.0925 3318.4184 3356.2109 3409.9728 3487.7220 10
# t3 <- arun2() 474.9235 494.7407 539.4406 641.2605 907.9072 10

关于r - 串联成组的矢量元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16407782/

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