[英]Comparing rows/vectors for identity in R using BY or APPLY?
我正在嘗試比較 R 中的一系列行和一個固定向量,並將它們標記為相同 (TRUE) 或不同 (FALSE)。 將問題想象成將一組測試響應與答案鍵進行比較。
我已經能夠使用循環和 COMPARE package 進行比較,但我無法使用更有效的方法(例如 BY、APPLY 或 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
如果有人可以建議為什么 APPLY 和 DDPLY 給我的結果與循環不同,以及我如何修改其中一個函數以避免使用循環,我將不勝感激。
你讓這太復雜了:
apply(test.answers,1,function(x){all(x[-1] == rep(3,6))})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.