如何合并条件数字向量的单元格?

时间:2015-04-09 13:31:37

标签: r

假设我有以下字符向量 A

A <- c("a","b","c","d","e","f","g","h")

以下数字向量 B

B <- c(1,4,6)

我想创建第三个字符向量 C ,它使用 B 合并 A ,这样:

C <- c("abc", "de", "fgh")

我该怎么做呢?提前谢谢!

2 个答案:

答案 0 :(得分:2)

您可以尝试:

C <- mapply(function(x1, x2){
                 paste(A[x1:x2], collapse="")
             }, 
             x1=B, 
             x2=c(B[-1]-1, length(A))
            )

C
#[1] "abc" "de"  "fgh"

C是通过将pastecollapse应用于A的每个子集来构建的,B由每个&#34; c(B[-1]-1, length(A))给出的索引定义索引&#34;,一方面,c(3, 5, 8)(此处为{{1}}),每个&#34;第二个索引&#34;另一方面。

答案 1 :(得分:2)

另一个类似的想法:

substring(paste(A, collapse = ""), B, c(B[-1] - 1, length(A)))
#[1] "abc" "de"  "fgh"