Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Accessing vectors with integer names

Tags:

r

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?

like image 517
isEmpty Avatar asked Jun 18 '26 05:06

isEmpty


1 Answers

Well, the simplest change is in the for statement:

for(c in as.character(communities)){
  v[c] = 1
}

Or vectorized:

v[as.character(communities)] <- 1

Or to have even more control you could do the match yourself:

idx <- match(communities, names(v))
v[idx] <- 1
like image 66
Tommy Avatar answered Jun 21 '26 12:06

Tommy