在 R 中应用相同()的行为 [英] Behavior of identical() in apply in R
本文介绍了在 R 中应用相同()的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这很奇怪.
apply( matrix(c(1,NA,2,3,NA,NA,2,4),ncol = 2), 1, function(x) identical(x[1], x[2]) )
#[1] FALSE TRUE TRUE FALSE
apply( data.frame(a = c(1,NA,2,3),b = c(NA,NA,2,4)), 1, function(x) identical(x[1], x[2]) )
#[1] FALSE FALSE FALSE FALSE
apply( as.matrix(data.frame(a = c(1,NA,2,3),b = c(NA,NA,2,4))), 1, function(x) identical(x[1], x[2]) )
#[1] FALSE FALSE FALSE FALSE
这是由于 joran 如下所示的 names 属性.我可以通过以下方式获得我期望的结果:
This is due to the names attribute as indicated below by joran. I can obtain the result I expected by:
apply( data.frame(a = c(1,NA,2,3),b = c(NA,NA,2,4)), 1, function(x) identical(unname(x[1]), unname(x[2])) )
或:
apply( data.frame(a = c(1,NA,2,3),b = c(NA,NA,2,4)), 1, function(x) identical(x[[1]], x[[2]]) )
有没有更自然的方法来解决这个问题?似乎应该有一个选项可以忽略属性,就像在 all.equal() 中一样.
Is there a more natural way to approach this? It would seem that there should be an option to ignore attributes, like in all.equal().
推荐答案
可能
mapply(identical, x$a, x$b)
#[1] FALSE TRUE TRUE FALSE
其中 x
是一个数据框.
where x
is a data frame.
顺便说一句,对数据框使用 apply
几乎总是一个错误.它会将数据框强制转换为矩阵,这通常会导致意想不到的结果.
As an aside, using apply
with a data frame is almost always a mistake. It will coerce the data frame to a matrix which often leads to unexpected results.
这篇关于在 R 中应用相同()的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文