【发布时间】:2016-06-03 00:23:23
【问题描述】:
R 将因子存储为整数。因此,当使用相同的函数时,如果两个因子具有不同的级别,则无法找到它们何时同名。
这是一个 MWE:
y <- structure(list(portfolio_date = structure(c(1L, 1L, 1L, 2L, 2L,
2L), .Label = c("2000-10-31", "2001-04-30"), class = "factor"),
security = structure(c(2L, 2L, 1L, 3L, 2L, 4L), .Label = c("Currency Australia (Fwd)",
"Currency Euro (Fwd)", "Currency Japan (Fwd)", "Currency United Kingdom (Fwd)"
), class = "factor")), .Names = c("portfolio_date", "security"
), row.names = c(10414L, 10417L, 10424L, 21770L, 21771L, 21774L
), class = "data.frame")
x <- structure(list(portfolio_date = structure(1L, .Label = "2000-10-31", class = "factor"),
security = structure(1L, .Label = "Currency Euro (Fwd)", class = "factor")),
.Names = c("portfolio_date", "security"), row.names = 10414L, class = "data.frame")
identical(y[1,], x)
返回FALSE
但是如果我们查看对象,它们看起来与用户相同
y[1,]
portfolio_date security
10414 2000-10-31 Currency Euro (Fwd)
x
portfolio_date security
10414 2000-10-31 Currency Euro (Fwd)
最终我希望能够执行以下操作:
apply(y, 1, identical, x)
10414 10417 10424 21770 21771 21774
TRUE TRUE FALSE FALSE FALSE FALSE
which(apply(y, 1, identical, x))
1 2
关于如何实现这一点的任何建议?谢谢。
【问题讨论】:
-
identical(droplevels(y[1,]), droplevels(x))或者all.equal(y[1,], x, check.attributes=F) -
感谢您的尝试,但使用相同的 droplevels 仍然返回 FALSE。此外,apply(y, 1, function(z) all.equal(z, x, check.attributes=F)) 有一些奇怪的输出。
-
您必须将列转换为字符。这是一个使用基数 R 的一行中的解决方案:apply(apply(y, 2, as.character), 1, same, apply(x, 2, as.character))
-
谢谢@Dave2e,你能把它列为答案以便我接受吗?
-
identical(droplevels(y[1,]), droplevels(x))返回 TRUE。请再次检查:)
标签: r