[R] how to "vectorize" this?

Akshaya Jha akshayaj at andrew.cmu.edu
Mon Jan 26 04:27:01 CET 2009


Hi,

I have the following datasets:
x=data I am looking through
key=a set of data with the codes I want

I have the following issue:
I want the subset of x which has a code contained in the key dataset.  That is, if x[i] is contained in the key dataset, I want to keep it.  Note that x may contain multiple of the same codes (or obviously none of that code as well)

I currently use two for-loops thusly in my R-code:

k=1
y=data.frame(1,stringsAsFactors=FALSE)
for(i in 1:length(x)){
for(j in 1:length(key)){

if(x[i]==key[j]){
y[k]=x[i]
k=k+1;
}

}
}
      
However, my dataset (x in this example) is pretty large, so I want to avoid using two for-loops.  Does anybody know an easier way to approach this?

Thanks




More information about the R-help mailing list