字符串在R的最后一个(也是在任何第n个)分隔符处分割,并在分隔符之前删除字符串

时间:2015-11-26 12:04:44

标签: r

我有一个向量vec。我需要在最后一次删除部件" /"并获取剩余的字符串并获取result。还请注意,我不能使用Perl兼容的regexp(即perl = FALSE)。我也希望看到第n个分隔符。

vec<-c("/apple/pineapple/mango/reg.sh_ttgs.pos","/apple/pipple/mgo/deh_ttgs.pos")

最后一个分隔符的结果

reg.sh_ttgs.pos , deh_ttgs.pos

第二个分隔符的结果

pineapple/mango/reg.sh_ttgs.pos, pipple/mgo/deh_ttgs.pos

依旧......

2 个答案:

答案 0 :(得分:5)

或者,您可以在char2end()包中使用qdap。您可以在函数中指定分隔符和要使用的分隔符(第1个,第2个等)。

library(qdap)

对于第二个分隔符,

char2end(vec, "/", 2)
#[1] "pineapple/mango/reg.sh_ttgs.pos" "pipple/mgo/deh_ttgs.pos"

对于最后一个分隔符,

char2end(vec, "/", 4)
#[1] "reg.sh_ttgs.pos" "deh_ttgs.pos" 

答案 1 :(得分:2)

一种方法是使用这样的函数(使用Assembly version attributes were not found in ... 获取字符串的位置,并gregexpr相应地对字符串进行子集化):

substring

输出:

get_string <- function(vec, n) {
  if(n == 'last'){
    positions <- lapply(gregexpr(pattern ='/',vec), function(x) x[length(x)] + 1)
  }else{
    positions <- lapply(gregexpr(pattern ='/',vec), function(x) x[n] + 1)
  }
  substring(vec, positions)
}

如果您只想要路径的最后一部分,您可以指定第n个'/'或仅指定'last'。

注意:我正在使用上面的> get_string(vec, 2) [1] "pineapple/mango/reg.sh_ttgs.pos" "pipple/mgo/deh_ttgs.pos" > get_string(vec, 'last') [1] "reg.sh_ttgs.pos" "deh_ttgs.pos" 语句,以防最后一个'/'的位置在实际向量的各个元素中不同。如果if-else的数量在所有元素中始终相同,则只需要/

相关问题