R Merge 4 lines into 1 line

I'm looking for the locations of 4 different substrings in x and trying to combine these four outputs into one aggregate string:

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

      

I would like to combine these four outputs and output this combined result as a text file with each item split on a new line.

merged_output
# 1
# 3
# 13
# 20

      

thank

+3


source to share


3 answers


Actually you can do it all at once using lookahead (?=)



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

      

+5


source


for example

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")

      



Now the file named tf

contains

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

      

+2


source


Not very automated, but

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

      

should do it.

+1


source







All Articles