[R] spliting an integer

Gabor Grothendieck ggrothendieck at gmail.com
Thu Oct 20 23:24:05 CEST 2005


On 10/20/05, Dimitri Szerman <dimitrijoe at ipea.gov.br> wrote:
> Hi there,
>
> >From the vector X of integers,
>
> X = c(11999, 122000, 81997)
>
> I would like to make these two vectors:
>
> Z= c(1999, 2000, 1997)
> Y =c(1 , 12 , 8)
>
> That is, each entry of vector Z receives the four last digits of each entry of X, and Y receives "the rest".
>

Some possibilities:

1. Use integer division and remainder (probably best solution):

	Y <- X %/% 10000
	Z <- X %% 10000

2. Convert to character and reduce to desired field:

	Y <- as.numeric(sub("....$", "", X))
	Z <- as.numeric(sub(".*(....)$", "\\1", X))

3. Insert a space between the two sets and read them in:

	read.table(textConnection(sub("(....)$", " \\1", X)),
		col.names = c("Y", "Z"))

4. Use encode at:

http://www.wiwi.uni-bielefeld.de/~wolf/software/R-wtools/decodeencode/decodeencode.rev

	encode(X, c(100, 10000))




More information about the R-help mailing list