1
나는 R에서 일련의 행과 고정 된 벡터를 비교하려고하고 동일하다고 (TRUE) 또는 동일하지 않은 (FALSE) 플래그로 표시하려고합니다. 문제를 답안 키에 대한 테스트 응답 세트를 비교하는 것으로 상상해보십시오.BY 또는 APPLY를 사용하여 R의 ID에 대한 행/벡터 비교?
나는 루프와 비교 패키지를 사용하여 작업 할 수 비교를 얻을 수 있었지만, 나는 그런 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가 나에게 루프와 다른 결과를 주는지 제안 할 수 있다면, 그리고 루프를 사용하지 않기 위해이 함수들 중 하나를 어떻게 수정할 수 있었는지 고맙게 생각한다.
덕분에, 그 해결책은 잘 작동합니다! 네, 분명히 너무 복잡하게 만들었습니다. – DartPrivateer