Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

r - Collapse vector to string of characters with respective numbers of consequtive occurences

I would like to collapse a CIGAR vector to a CIGAR string. By CIGAR vector to String I mean the following:

I want a function that converts:

cigar.vector = c("M", "M", "I", "I", "M", "I", "", "M", "D", "D", "M", "I", "D", "M", "I")

to this:

cigar.string = "2M2I1M1I1M2D1M1I1D1M1I"

and viceversa.

Note that there is a "" (empty character), that does not count. thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

rle seems the obvious choice here:

rcv <- rle(cigar.vector[cigar.vector!=""])
paste0(rcv$lengths,rcv$values,collapse="")
#[1] "2M2I1M1I1M2D1M1I1D1M1I"

If you want to get fancy, you could also exploit the fact that rle gives a list of length 2:

paste(do.call(rbind,rle(cigar.vector[cigar.vector!=""])),collapse="")
#[1] "2M2I1M1I1M2D1M1I1D1M1I"

Going backwards will be impossible if only given the result (assign above to result), as it has lost information for the "" cases. Excluding those cases, you can get close enough with something like:

backwards <- rep(
  unlist(strsplit(result,"\d+"))[-1],
  as.numeric(unlist(strsplit(result,"[^0-9]")))
)
identical(cigar.vector[cigar.vector!=""],backwards)
#[1] TRUE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...