1

我对 R 很陌生,我可能会遗漏一些信息,但我无法理解这种行为:

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)
}

其中topo具有以下结构:

 2l59mm6jc8pae32vilsr99ljp0 40iml67hpjsr8o1oo7f4oin706
 3359mm6jc8pae32vilsr99ljp0 411iml67hpjsr8o1oo7f4oin706
 ...

我想做的是遍历第一列并usr从第一列中查看匹配项,然后将第二列的内容添加到n我返回的 中。

发生的事情是我在输出中得到一些数字:1916. 如果我尝试调试它,我会得到以下答案:

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

我究竟做错了什么?

4

2 回答 2

5

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.

于 2013-10-31T17:04:11.623 回答
1

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"
于 2013-10-31T17:03:43.367 回答