mercoledì 20 giugno 2007

String manipulation, insert delim

From the list, as usual:

I want to be able to insert delimiters, say commas, into a string
of characters at uneven intervals such that:

foo<-c("haveaniceday")# my string of character
bar<-c(4,1,4,3) # my vector of uneven intervals,bar) # some function that places delimiters appropriately
have,a,nice,day # what the function would ideally return


paste(read.fwf(textConnection(foo), bar, = TRUE), collapse = ",")
[1] "have,a,nice,day"


my.function <- function(foo, bar){
# construct a matrix with start/end character positions
start <- head(cumsum(c(1, bar)), -1) # delete last one
sel <- cbind(start=start,end=start + bar -1)
strings <- apply(sel, 1, function(x) substr(foo, x[1], x[2]))
paste(strings, collapse=',')

my.function(foo, bar)
[1] "have,a,nice,day"

Nessun commento:

Posta un commento