[R] Assignment of values with different indexes

arun smartpink111 at yahoo.com
Thu Dec 6 05:49:04 CET 2012



Hi,

Would it be okay to use:
 y<-na.omit(y[myindex]<-x)
y
# [1] -1.36025132 -0.57529211  1.18132359  0.41038489  1.83108252 -0.03563686
 #[7]  1.25267314  1.08311857  1.56973422 -0.30752939

A.K.


----- Original Message -----
From: Brian Feeny <bfeeny at mac.com>
To: "r-help at r-project.org help" <r-help at r-project.org>
Cc: 
Sent: Wednesday, December 5, 2012 9:47 PM
Subject: [R] Assignment of values with different indexes


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

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list