简体   繁体   中英

Differences applying “identical” function using lapply and apply

Using the lapply and the apply functions to test for identical values yields inconsistent results.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM