Vasily A
Vasily A

Reputation: 8646

get the name of a member of named vector cycled in `for`

I have a named vector: myvec <- c(a='aaa', b='bbb', c='ccc') and I process it with for:

for (memb in myvec){
 cat(memb, '\n');
}

This works fine, but what if I want to get the names in the same cycle, something like that:

for (memb in myvec){
 cat(name(memb)); # something for `name()`
 cat(': ', memb, '\n');
}

Upvotes: 0

Views: 45

Answers (2)

pcantalupo
pcantalupo

Reputation: 2226

It will depend on what you do with duplicates. Here's my simple solution:

myvec <- c(a='aaa', b='bbb', c='ccc',d='bbb')
for (memb in myvec){
  cat(names(myvec[myvec==memb])); # returns all names of the value
  cat(': ', memb, '\n');
}

Output:

a:  aaa 
b d:  bbb 
c:  ccc 
b d:  bbb 

Upvotes: 0

ikkyle
ikkyle

Reputation: 46

Is there any reason you couldn't loop using the index of myvec?

myvec <- c(a='aaa', b='bbb', c='ccc', b='ddd')

for(i in 1:length(myvec)){
    cat(names(myvec)[i])
    cat(': ', myvec[i], '\n')
} 

Upvotes: 2

Related Questions