I have a large function which has a vector defined as follows:
v <- mat.or.vec(length(communities), 1)
names(v) <- communities
And, I access the elements of v in a loop as follows
for(c in communities){
v[c] = 1
}
When this code was written and tested, the list communities was a list of strings. But today when I ran this on a dataset which had all integer values in the communities list, my function crashed. It took me a while to figure out that when communities is a integer list, c is an integer and v[c] access the cth element of v and not the element of v with name c.
I can fix this problem by using something like v[as.character(c)]. There are many such variables which face the same problem.
Is there a more elegant solution to this problem?
Well, the simplest change is in the
forstatement:Or vectorized:
Or to have even more control you could do the match yourself: