[R] Assignment of values with different indexes

Brian Feeny bfeeny at mac.com
Thu Dec 6 03:47:56 CET 2012


I would like to take the values of observations and map them to a new index.  I am not sure how to accomplish this.  The result would look like so:

x[1,2,3,4,5,6,7,8,9,10]
becomes
y[2,4,6,8,10,12,14,16,18,20]

The "newindex" would not necessarily be this sequence, but a sequence I have stored in a vector, so it could be all kinds of values.  here is what happens:

> x <- rnorm(10)
> myindex <- seq(from = 1,to = 20, by = 2)
> y <- numeric()
> y[myindex] <- x
> y
 [1] -0.03745988          NA -0.09078822          NA  0.92484413          NA  0.32057426          NA
 [9]  0.01536279          NA  0.02200198          NA  0.37535438          NA  1.46606535          NA
[17]  1.44855796          NA -0.05048738

So yes, it maps the values to my new indexes, but I have NA's.  The result I want would look like this instead:


 [1] -0.03745988          
 [3] -0.09078822           
 [5] 0.92484413           
 [7] 0.32057426         
 [9]  0.01536279           
 [11] 0.02200198           
 [13] 0.37535438           
 [15] 1.46606535         
 [17]  1.44855796          
 [19] -0.05048738


and remove the NA's.  I tried this with na.omit() on x, but it looks like so:

> x <- rnorm(10)
> myindex <- seq(from = 1,to = 20, by = 2)
> y <- numeric()
> y[myindex] <- na.omit(x)
> y
 [1]  0.87399523          NA -0.39908184          NA  0.14583051          NA  0.01850755          NA
 [9] -0.47413632          NA  0.88410517          NA -1.64939190          NA  0.57650807          NA
[17]  0.44016971          NA -0.56313802

Brian



More information about the R-help mailing list