Split vector of strings and paste subset of resulting elements into a new vector

前端 未结 4 959
悲&欢浪女
悲&欢浪女 2021-02-19 23:52

Define

z<- as.character(c(\"1_xx xx xxx_xxxx_12_sep.xls\",\"2_xx xx xxx_xxxx_15_aug.xls\"))

such that

> z
[1] \"1_xx xx x         


        
4条回答
  •  盖世英雄少女心
    2021-02-20 00:44

    An alternative along the same lines of @Joran's Answer is this:

    foo <- function(x) {
        o <- paste(x[c(1,4,5)], collapse = "_")
        substr(o, 1, nchar(o) - 4) 
    }
    
    sapply(strsplit(z, "_"), foo)
    

    The differences are minor - I use collapse = "_" and nchar() but other than that it is similar.

    You can write this as a one-liner

    sapply(strsplit(z, "_"), 
           function(x) {o <- paste(x[c(1,4,5)], 
                                   collapse = "_"); substr(o, 1, nchar(o)-4)})
    

    but writing the custom function to apply is nicer.

提交回复
热议问题