Reputation: 583
Is there a faster way to search for indices rather than which %in%
R.
I am having a statement which I need to execute but its taking a lot of time.
statement:
total_authors<-paper_author$author_id[which(paper_author$paper_id%in%paper_author$paper_id[which(paper_author$author_id%in%data_authors[i])])]
How can this be done in a faster manner?
Upvotes: 2
Views: 382
Reputation: 121127
Don't call
In light of sgibb's comment, you can keep which
. R accepts logical vectors as indices, so the call is superfluous.which
if you are sure that you will also get at least one match. (If there are no matches, then which
returns an empty vector and you get everything instead of nothing. See Unexpected behavior using -which() in R when the search term is not found.)
Secondly, the code looks a little cleaner if you use with
.
Thirdly, I think you want a single index with &
rather than a double index.
total_authors <- with(
paper_author,
author_id[paper_id %in% paper_id & author_id %in% data_authors[i]
)
Upvotes: 1