1
z=c("abcD9","recde6","7gfbe","dvS1","MNM09")
d=c("abcD9","recde6","abcD9","bgfh123","dvS1")
y <- numeric(length=25)
k<-1
for ( i in 1:5) {
  for (j in  1:5) {
    a <- (z[i]==d[j])
    if( a==TRUE) y[k] <- j else y[k] <- 0
  }
  k<-k+1
}

我应该将结果作为“y”作为向量 (1 0 3 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0)

4

3 回答 3

3

我会采用更矢量化/应用循环的方法:

y = do.call('c', lapply(z, function(x) ifelse(x == d, seq_along(d), 0)))
[1] 1 0 3 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0

或使用expand.grid

df = data.frame(expand.grid(d = d, z = z, stringsAsFactors = FALSE), 
                y = rep(seq_along(d), length(z)))
with(df, ifelse(z == d, y, 0))
于 2013-06-05T09:47:02.720 回答
3

You could eliminate the loop and do something vectorised like so:

pos <- t( outer( z , d , FUN = "==" ) )
pos[ pos == TRUE ] <- which( pos , arr.ind = TRUE )[,1]
as.vector(pos)
#[1] 1 0 3 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0
于 2013-06-05T09:51:17.180 回答
2

k<-k+1如果您进入内部循环,它将起作用:

for ( i in 1:5)
{
  for (j in  1:5)
  {
    a <- (z[i]==d[j])
    if( a==TRUE)
      y[k] <- j
    else
      y[k] <- 0
    k<-k+1  
  }  
}

结果(y):

[1] 1 0 3 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0

顺便说一句:您可以使用以下命令获得相同的结果:

tmp <- sapply(z, function(vec1) !is.na(match(d, vec1)))
y <- numeric(length = length(tmp))
y[unlist(tmp)] <- which(tmp, arr.ind = TRUE)[ , 1]
于 2013-06-05T09:34:05.440 回答