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)
答案 0 :(得分: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))
答案 1 :(得分:3)
你可以消除循环并做一些像这样的矢量化:
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
答案 2 :(得分: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]