[R] substring and paste character with a for loop

Ben Bolker bbolker at gmail.com
Thu Feb 3 17:41:06 CET 2011


Chris82 <rubenbauar <at> gmx.de> writes:

> 
> 
> Hello R users,
> 
> I have a little problem with a for loop.
> Below there is an simple example of my problem.
> 
> I want to delet the commas in the character string. Fore this reason I
> create a for loop to unpick the string and rebuild him without the commas.
> The problem is, that "paste" does not work in the loop as I expected.
> 
> text <- "aaa,bbb,ccc,ddd"
> 
> characterseq <- seq(1,15,4)
> 
> for (i in characterseq ){
> m <- paste(substring(text,i,i+2),sep = "")
> }
> 
> > m
> [1] "ddd"
> 
> m should be "aaabbbcccddd" and not just "ddd"
> 

  If you want to delete commas, what about

 gsub(",","",c("aaa,bbb,ccc,ddd"))
[1] "aaabbbcccddd"

?

  The problem with your loop is that you are not building m; you
would need paste(m,substring(text,i,i+2),sep="")



More information about the R-help mailing list