2012-04-09 3 views
1

私はRで一連の行と固定ベクトルを比較しようとしていて、それらを同一(TRUE)または同一でない(FALSE)ようにフラグを立てます。この問題を、一連のテスト回答を回答キーと比較することを想像してみてください。BYまたはAPPLYを使用してRのIDの行/ベクトルを比較しますか?

私はループとCOMPAREパッケージを使用して動作するように比較を取得することができたが、私はそのようBY、適用したりDDPLYとして、より効率的な方法を使用して、それを複製することができませんでした:

test.answers <- as.data.frame(rbind(c(ID="A",rep(3, 6)), c(ID="B",6:1), c(ID="C",1:6))) 

library(compare) 

# Compare using a loop 
for (i in 1:length(test.answers)) 
    { 
    test.answers$Static1[i] <- isTRUE(compare(as.data.frame(rbind(rep(3, 6))), 
              test.answers[i,2:7], allowAll=TRUE)) 
    } 
test.answers # This is correct! 

staticfn <- function(x) 
    { 
    isTRUE(compare(as.data.frame(rbind(rep(3, 6))), 
       test.answers[2:7], allowAll=TRUE)) 
    } 

# Compare using APPLY 
test.answers$Static2 <- apply(test.answers, 1, staticfn) 
test.answers # This is incorrect! 

# Compare using BY 
test.answers$Static3 <- by(test.answers, test.answers$ID, staticfn) 
test.answers # This is incorrect! 

# Compare using DDPLY 
library(plyr) 
test.answers <- ddply(test.answers, .(ID), { staticfn }) 
test.answers # This is incorrect! 


# Results 

    ID V2 V3 V4 V5 V6 V7 Static1 Static2 Static3 
1 A 3 3 3 3 3 3 TRUE TRUE TRUE 
2 B 6 5 4 3 2 1 FALSE TRUE TRUE 
3 C 1 2 3 4 5 6 FALSE TRUE TRUE 

    ID V1 
1 A TRUE 
2 B TRUE 
3 C TRUE 

I誰かがなぜAPPLYとDDPLYが私にループとは異なる結果をもたらしているのかを示唆することができ、ループを使用しないようにこれらの関数のどれを修正することができるか感謝します。あなたは、これはあまりにも複雑になっている

答えて

3

apply(test.answers,1,function(x){all(x[-1] == rep(3,6))}) 
+0

おかげで、そのソリューションは素晴らしい作品!はい、私はそれをあまりにも複雑にしていました。 – DartPrivateer

関連する問題