使用R

时间:2016-06-22 06:18:57

标签: regex r

我有一组字符串x,例如:

[1] "0000000000000000000000000000000000000Y"   "9000000000D00000000000000000000Y"        
[3] "0000000000000D00000000000000000000X"      "000000000000000000D00000000000000000000Y"
[5] "000000000000000000D00000000000000000000Y" "000000000000000000D00000000000000000000Y"
[6]"000000000000000000000000D0000000011011D1X"

我想提取特定字符的最后位置,如1.我正在运行此代码:

ifelse(grepl("1",x),rev(gregexpr("1",x)[[1]])[1],50)

但是这对所有元素都返回-1。我该如何纠正?

enter image description here

2 个答案:

答案 0 :(得分:0)

在基数R中,以下内容返回最后一个匹配的# Make some toy data toydata <- c("001", "007", "00101111Y", "000AAAYY") # Find last postion last_pos <- sapply(gregexpr("1", toydata), function(m) m[length(m)]) print(last_pos) #[1] 3 -1 8 -1 的位置。

-1

只要模式不匹配,它就会返回function updatebroker() { var result = $("#broker_form").serialize(); $.ajax({ type: 'POST', url: site_url + "mycontacts/updatebroker", data: result, success: function(response) { $('.insertmessage').attr('class', '').addClass('text-success').html('Updated successfully.').show(); window.location.href = site_url + 'mycontacts/getcommonlist'; setTimeout(function() { $(".insertmessage").hide(); window.location.href = site_url + 'mycontacts/getcommonlist'; $("#tabs").tabs(/* ? ? ? ? ? ? ? ? ? ? ? ? ? */); }, 3000); } }); }

答案 1 :(得分:0)

我们可以使用stri_locate_last中的stringi。如果没有匹配项,则会返回NA

library(stringi)
r1 <- stri_locate_last(v1, fixed=1)[,1]
r1
#[1] NA NA NA NA NA NA 40
nchar(v1)
#[1] 38 32 35 40 40 40 41

如果我们需要用字符数替换NA值

ifelse(is.na(r1), nchar(v1), r1)

数据

v1 <-  c("0000000000000000000000000000000000000Y", 
      "9000000000D00000000000000000000Y", 
      "0000000000000D00000000000000000000X",
      "000000000000000000D00000000000000000000Y",
      "000000000000000000D00000000000000000000Y", 
      "000000000000000000D00000000000000000000Y", 
      "000000000000000000000000D0000000011011D1X")