r - How to filter a set of value from matrix with citeria in a vector without a loop? -


i have matrix source (a), first column key, , second value each key.

__0_1                    22034 __1000000000000_1        34310 __1000000000000_2        38608 __1000000000_1           18829 __1000_1                 38674 __11_november_1          21566 __11_plus_1              35908 __12_1                   25784 __14_july_1              28671 __15_may_organization_1  36358 

and vector b subset of key need assign value base on matrix a. b:

__14_july_1 __1000000000_1 _15_may_organization_1 

here code find value b matrix a:

for (i in 1:length(b)){  rlst<-a[a[,1]==b[i],2]; } 

it work & b small. real data big, , loop make me lost lot of time.
tried command %in%,subset. not working problem. please me solve problem without for.

i'm going assume expect 1 match each value of b. here sample data sets

a<-data.frame(     v1 = c("__0_1", "__1000000000000_1", "__1000000000000_2",      "__1000000000_1", "__1000_1", "__11_november_1", "__11_plus_1",      "__12_1", "__14_july_1", "__15_may_organization_1"),      v2 = c(22034l,      34310l, 38608l, 18829l, 38674l, 21566l, 35908l, 25784l, 28671l,      36358l) ) b<-c("__14_july_1", "__15_may_organization_1", "__1000000000_1") 

(notice switched position of 2 values in b.)

two ways can extract data want are

a[a[,1] %in% b, ] #                         v1    v2 # 4           __1000000000_1 18829 # 9              __14_july_1 28671 # 10 __15_may_organization_1 36358 

and

a[match(b,a[,1]),] #                         v1    v2 # 9              __14_july_1 28671 # 10 __15_may_organization_1 36358 # 4           __1000000000_1 18829 

note first way preserves order of rows in a, while second method returns rows in order of b seems closest loop have done.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -