1

给定以下数据:

questionTagMatrix <- data.frame( question1=c("0","1","0"), question2=c("1","0", "0"), question3=c("0","1","0"), question4=c("0","1","1")  )
rownames(questionTagMatrix)[1] <- "php"
rownames(questionTagMatrix)[2] <- "html"
rownames(questionTagMatrix)[3] <- "javascript"

newQuestion <- data.frame( newquestion=c("0","1","0") )
rownames(newQuestion)[1] <- "php"
rownames(newQuestion)[2] <- "html"
rownames(newQuestion)[3] <- "javascript"

如何找到questionTagMatrix等于的所有列newQuestion

4

2 回答 2

2

您可以使用apply来查找列:

questionTagMatrix[apply(questionTagMatrix, 2, function(x) 
                                               all(x == as.matrix(newQuestion)))]

的所有列questionTagMatrix都与 进行比较newQuestion。结果:

#            question1 question3
# php                0         0
# html               1         1
# javascript         0         0
于 2013-11-04T14:20:04.510 回答
0

使用 的矢量化解决方案colSums

 questionTagMatrix[,colSums(questionTagMatrix == newQuestion)
                    ==nrow(questionTagMatrix)]

          question1 question3
php                0         0
html               1         1
javascript         0         0

PS newQuestion 在这里是一个向量:

newQuestion =c("0","1","0") ## not data.frame( newquestion=c("0","1","0") )

仅获取问题名称:

names(questionTagMatrix)[colSums(questionTagMatrix == newQuestion)
+                   ==nrow(questionTagMatrix)]
[1] "question1" "question3"
于 2013-11-04T14:22:34.460 回答