[英]Differences applying “identical” function using lapply and apply
Using the lapply
and the apply
functions to test for identical values yields inconsistent results. 使用lapply
和apply
函数测试相同的值会产生不一致的结果。
I'm doing the following: 我正在执行以下操作:
test <- read.table(text="
V6 V7 V8
1 109 109 109
2 199 199 199
3 198 198 198
4 199 199 199
5 198 198 198
6 199 199 199", header=T)
for (i in 1:nrow(test)){
print(identical(test[1, 1],
test[1, 2],
test[1, 3]))
}
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
# [1] TRUE
do.call("rbind", lapply(1:nrow(test),
function(x){
identical(test[x, 1],
test[x, 2],
test[x, 3])
}))
# [,1]
# [1,] TRUE
# [2,] TRUE
# [3,] TRUE
# [4,] TRUE
# [5,] TRUE
# [6,] TRUE
apply(test, 1, function(x){
identical(x[1], x[2], x[3])
})
# 1 2 3 4 5 6
# FALSE FALSE FALSE FALSE FALSE FALSE
I don't really understand this inconsistency. 我不太了解这种矛盾。
It has to do with column names of your data. 它与数据的列名有关。 Consider this example: 考虑以下示例:
a <- t(matrix(c(1, 1, 1, 2, 2, 2), 3, 2))
apply(a, 1, function(x) identical(x[1], x[2], x[3]))
[1] TRUE TRUE
colnames(a) <- letters[1:3]
apply(a, 1, function(x) identical(x[1], x[2], x[3]))
[1] FALSE FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.