2015-07-03 69 views
3

我在尋找的4個不同的子串x中的位置,並試圖以這四個輸出合併爲一個字符串累計:[R 4個合併成字符串1個字符串

x <- ("AAABBADSJALKACCWIEUADD") 
outputA <- gregexpr(pattern = "AAA", x) 
outputB <- gregexpr(pattern = "ABB", x) 
outputC <- gregexpr(pattern = "ACC", x) 
outputD <- gregexpr(pattern = "ADD", x) 

我想合併這四個輸出並將該合併結果作爲文本文件輸出,每個元素以新行分隔。

merged_output 
# 1 
# 3 
# 13 
# 20 

謝謝

回答

5

其實你可以使用一個超前(?=)

gregexpr("A(?=AA|BB|CC|DD)", x, perl=T)[[1]] 
# [1] 1 3 13 20 
# attr(,"match.length") 
# [1] 1 1 1 1 
# attr(,"useBytes") 
# [1] TRUE 
2

一次例如做這一切

library(stringi) 
cat("merged_output", 
    paste("#", 
      stri_locate_first_fixed(pattern = c("AAA", "ABB", "ACC", "ADD"), ("AAABBADSJALKACCWIEUADD"))[, "start"]), 
    file = tf <- tempfile(fileext = ".txt"), 
    sep = "\n") 

現在,在tf命名的文件包含

> merged_output 
> # 1 
> # 3 
> # 13 
> # 20 
1

自動程度不高,但

cat(paste(c(outputA[[1]][1], outputB[[1]][1], outputC[[1]][1], outputD[[1]][1]), 
      collapse = "\n"), 
    file = "outputfile.txt") 

應該這樣做。