Reputation: 75
I'm trying to compare elements from 2 vectors in this way,but I get result just for the first element.
>ex1<-c('gdgdg','dd','fffff','ssdsds')
fuct1<-function(x){
for(i in 1:length(x)){
ex2<-c('xxxx','ddd','ddd','ddd','dddd')
match<-agrep(x[i],ex2[i],value='true')
return(match[i])
}
}
>fuct1(ex1)
By this example I want to compare 'gdgdg' and 'xxxx'(first elements from each vector) 'dd'and 'ddd'(second ones) and so on...,As result I would like to have something as (NA,ddd,NA,NA). My result with my code is just NA. Thanks for your help.
Upvotes: 1
Views: 3868
Reputation: 121568
T think you are looking for mapply
mapply(agrep,ex1,ex2,value=TRUE)
But this assume that your 2 vectors have the same length.
Upvotes: 1
Reputation: 1237
Maybe this is what you want:
ex1<-c('gdgdg','ddd','fffff','ssdsds')
match<-"TROLOLOL"
fuct1<-function(x){
for(i in 1:length(x)){
ex2<-c('xxxx','ddd','ddd','dddd')
match<-c(match,agrep(x[i],ex2[i],value=TRUE))
}
return(match)
}
fuct1(ex1)[-1]
[1] "ddd"
You can complete this if you want NAs I guess :)
Upvotes: 0
Reputation: 4995
You want to use sapply
here:
ex2<-c('xxxx','ddd','ddd','ddd','dddd')
sapply(ex1, function(x) agrep(x, ex2))
$gdgdg
integer(0)
$dd
[1] 2 3 4 5
$fffff
integer(0)
$ssdsds
integer(0)
Upvotes: 4