拆分字符串向量并将结果元素的子集粘贴到新向量中 [英] Split vector of strings and paste subset of resulting elements into a new vector
本文介绍了拆分字符串向量并将结果元素的子集粘贴到新向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
定义
z<- as.character(c("1_xx xx xxx_xxxx_12_sep.xls","2_xx xx xxx_xxxx_15_aug.xls"))
这样
> z
[1] "1_xx xx xxx_xxxx_12_sep.xls" "2_xx xx xxx_xxxx_15_aug.xls"
我想创建一个矢量 w 使得
I want to create a vector w such that
> w
[1] "1_12_sep" "2_15_aug"
即,将 z 的每个元素用 _ 分割,然后连接元素 1,4,5,删除 .xls后者.
That is, split each element of z by _ and then join elements 1,4,5, with the .xls removed from the latter.
我可以管理拆分部分,但不确定要提供什么功能,例如类似
I can manage the split part, but not sure what function to provide, e.g something like"
w <- as.character(lapply(strsplit(z,"_"), function(x) ???))
推荐答案
您可以使用 strsplit
、substr
和 lapply
的组合来做到这一点>:
You can do this using a combination of strsplit
, substr
and lapply
:
y <- strsplit(z,"_",fixed=TRUE)
lapply(y,FUN=function(x){paste(x[1],x[4],substr(x[5],1,3),sep="_")})
这篇关于拆分字符串向量并将结果元素的子集粘贴到新向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文