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

前端 未结 4 958
悲&欢浪女
悲&欢浪女 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:20

    One call to gsub (and some regex magic based on @Andrie's answer) can do this. See ?regexp for details on what I used in the pattern and replacement (back-reference) arguments.

    gsub("^(\\d+_).*_(\\d+_\\w*).xls", "\\1\\2", z)
    # [1] "1_12_sep" "2_15_aug"
    

提交回复
热议问题