sapply - Is there a way to vectorize this operation using xapply in R -


i have vector

a <- c("there and", "walk and", "and see", "go there", "was i", "and see",  "i walk", "to go", "to was") 

and data frame bg where

bg <- data.frame(term=c("there and", "walk and", "and see", "go there", "was i", "and see", "i walk", "to go", "to was"), freq=c(1,1,2,1,1,2,1,1,1)) 

i need create vectorized version following code using either sapply,tapply, or vapply or apply etc

 d <- null  for(i in 1:length(a)){      temp <- filter(bg,term==a[i])      d <- rbind(d,temp)  } 

the need search bg data when term==a[i] , create data frame d

i need vector version loops excruciatingly slow in r.

here sample data

> bg        term freq 1 there ,    1 2  walk ,    1 3   , see    2 4  go there    1 5        1 6   , see    2 7    walk    1 8     go    1 9       1 

and

>d        term freq 1 there ,    1 2  walk ,    1 3   , see    2 4   , see    2 5  go there    1 6        1 7   , see    2 8   , see    2 9    walk    1 10    go    1 11      1 

thanks

this becomes merge operation, little twist make sure row order follows order in a:

out <- merge(bg, list(term=a, sortid=seq_along(a)), by="term") out[order(out$sortid),]  #        term freq sortid #7  there ,    1      1 #10  walk ,    1      2 #1    , see    2      3 #3    , see    2      3 #5   go there    1      4 #11        1      5 #2    , see    2      6 #4    , see    2      6 #6     walk    1      7 #8      go    1      8 #9        1      9 

or in data.table 1.9.5, nod @akrun:

library(data.table) out <- data.table(term=a, sortid=seq_along(a))[setdt(bg), on='term'] out[order(out$sortid)] 

or in dplyr:

left_join(data.frame(term=a), bg) 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -