将字符向量转换为子串的新向量

时间:2018-08-03 12:04:05

标签: r regex string

假设我有一个字符向量a <- c("take", "me", "home", "run", "do", "eat")。我想创建一个可以接受此字符向量和某个值n的函数,然后说n=2,您将得到:

c("take me", "home run", "do eat")

如果n=3,您将得到:

c("take me home", "run do eat")

最有效的方法(最快,最具扩展性)是什么?

3 个答案:

答案 0 :(得分:2)

a <- c("take", "me", "home", "run", "do", "eat")
l <- length(a)

n <- 2    
tapply(a, rep(1:ceiling(l/n), rep(n, ceiling(l/n)))[1:l], paste, collapse = " ")
         1          2          3 
 "take me" "home run"   "do eat" 

n <- 3
tapply(a, rep(1:ceiling(l/n), rep(n, ceiling(l/n)))[1:l], paste, collapse = " ")
             1              2 
"take me home"   "run do eat" 

n <- 4
tapply(a, rep(1:ceiling(l/n), rep(n, ceiling(l/n)))[1:l], paste, collapse = " ")
                 1                  2 
"take me home run"           "do eat" 

答案 1 :(得分:1)

您可以尝试一下。

library(dplyr)
a <- c("take", "me", "home", "run", "do", "eat")

group_string <- function(vec, n){
    df <- data_frame(string = vec, ind = ceiling(grep("^.*?", a)/ n)) %>% 
        group_by(ind) %>% 
        summarise(string = paste(string, collapse = " "))
    return(df$string)
}

group_string(a,2)
[1] "take me"  "home run" "do eat"  

group_string(a,3)
[1] "take me home" "run do eat"  

答案 2 :(得分:0)

此功能可以解决问题。

conFun <- function(v,n){
  while(length(v)>0){
    print(v[1:n])
    v <- v[-(1:n)]
  }
}

conFun(a,3)

[1] "take" "me"   "home"
[1] "run" "do"  "eat"