Pio
Pio

Reputation: 4064

Loop through list and append in R

I'm quite new to R and I may be missing some info, but I cannot wrap my head around this behavior:

neighbors<-function(topo,usr){
  n = NULL
  for (i in 1:length(topo[,1])){
    if (topo[i,1] == usr){
      n <- append(n,topo[i,2])
    }
  }
return(n)
}

Where topo has the following structure:

 2l59mm6jc8pae32vilsr99ljp0 40iml67hpjsr8o1oo7f4oin706
 3359mm6jc8pae32vilsr99ljp0 411iml67hpjsr8o1oo7f4oin706
 ...

What I would like to do is loop through the first column and see the matches with usr from the first column and add the content of the second column to n, that I return.

What happens is I get some numbers in the output: 19 and 16. If I try to debug it I was getting the following answer:

   [1] vi4govpcqjnf6imquadf9ae4f0
   20 Levels: 2l59mm6jc8pae32vilsr99ljp0 40iml67hpjsr8o1oo7f4oin706 ... vvqp3im2g3r90ibv56817asfq7
   [1] 19
   [1] nb9b1vh6ocaqsmgp8dv1s22f61
   20 Levels: 2l59mm6jc8pae32vilsr99ljp0 40iml67hpjsr8o1oo7f4oin706 ... vvqp3im2g3r90ibv56817asfq7
   [1] 19 16
   [1] 19 16

What am I doing wrong?

Upvotes: 1

Views: 957

Answers (2)

sckott
sckott

Reputation: 5893

Does this do what you want? And I used stringsAsFactors=FALSE because in your code you are potentially matching a factor against a character string

topo <- data.frame(a=c('2l59mm6jc8pae32vilsr99ljp0','40iml67hpjsr8o1oo7f4oin706'),
               b=c('3359mm6jc8pae32vilsr99ljp0','411iml67hpjsr8o1oo7f4oin706'), 
               stringsAsFactors=FALSE)

neighbors <- function(topo, usr){ 
    n = c()
    for (i in seq_along(usr)){
      if (topo[i,1] == usr[i])
         n[i] <- topo[i,2]
    }
    return( n )
}

<r> neighbors(topo=topo, usr='2l59mm6jc8pae32vilsr99ljp0')
[1] "3359mm6jc8pae32vilsr99ljp0"

<r> neighbors(topo=topo, usr=c('2l59mm6jc8pae32vilsr99ljp0','40iml67hpjsr8o1oo7f4oin706'))
[1] "3359mm6jc8pae32vilsr99ljp0"  "411iml67hpjsr8o1oo7f4oin706"

Upvotes: 1

Se&#241;or O
Se&#241;or O

Reputation: 17412

A better approach would be:

n = topo[,2][topo[,1] %in% usr]

Without seeing your data set I can't say for sure, but there's two potential problems I see in your code:

1) topo columns 1 and 2 are factors. You should convert them to character.

2) If usr has more than one element, if(topo[i,1] == usr) will not work as intended.

Upvotes: 5

Related Questions