R - 使用 Reduce 比较对象向量
R - Compare vector of objects using Reduce
我正在尝试使用 Reduce
比较对象的向量 a
- all.equal 无效
- == 适用于数字,但不适用于对象。
我更喜欢不使用现有包但仅使用 R 核心功能的解决方案
示例(简化使用数值向量而不是对象):
test <- c(1,1,1,1,1)
Reduce("==",test)
[1] TRUE
我不明白 为什么 == 有效而 all.equal 不
Reduce(all.equal,test)
[1] "Modes: character, numeric"
[2] "Lengths: 3, 1"
[3] "target is character, current is numeric"
最后的评论:
这是不是重复的。我对比较 对象而不是数值
的解决方案感兴趣
比较数值向量的元素:参见Whosebug上现有的解决方案
Test for equality among all elements of a single numeric vector
您可以在 sapply
中尝试 identical
并将每个元素与第一个元素进行比较。
x <- list(list(1), list(1))
all(sapply(x[-1], identical, x[[1]]))
#[1] TRUE
x <- list(list(1), list(2))
all(sapply(x[-1], identical, x[[1]]))
#[1] FALSE
这是一个函数,如果列表中元素的所有成对比较都相同,则返回 TRUE:
all_pairs_equal <- function(elements) {
all(mapply(function(x, y) identical(elements[x], elements[y]), 1, seq(1, length(elements))))
}
all_pairs_equal(list(iris, iris, iris))
#> [1] TRUE
all_pairs_equal(list(1, 1, 1))
#> [1] TRUE
all_pairs_equal(list(iris, iris, 2))
#> [1] FALSE
由 reprex package (v2.0.1)
于 2021-10-05 创建
我正在尝试使用 Reduce
比较对象的向量 a- all.equal 无效
- == 适用于数字,但不适用于对象。
我更喜欢不使用现有包但仅使用 R 核心功能的解决方案
示例(简化使用数值向量而不是对象):
test <- c(1,1,1,1,1)
Reduce("==",test)
[1] TRUE
我不明白 为什么 == 有效而 all.equal 不
Reduce(all.equal,test)
[1] "Modes: character, numeric"
[2] "Lengths: 3, 1"
[3] "target is character, current is numeric"
最后的评论:
这是不是重复的。我对比较 对象而不是数值
的解决方案感兴趣比较数值向量的元素:参见Whosebug上现有的解决方案 Test for equality among all elements of a single numeric vector
您可以在 sapply
中尝试 identical
并将每个元素与第一个元素进行比较。
x <- list(list(1), list(1))
all(sapply(x[-1], identical, x[[1]]))
#[1] TRUE
x <- list(list(1), list(2))
all(sapply(x[-1], identical, x[[1]]))
#[1] FALSE
这是一个函数,如果列表中元素的所有成对比较都相同,则返回 TRUE:
all_pairs_equal <- function(elements) {
all(mapply(function(x, y) identical(elements[x], elements[y]), 1, seq(1, length(elements))))
}
all_pairs_equal(list(iris, iris, iris))
#> [1] TRUE
all_pairs_equal(list(1, 1, 1))
#> [1] TRUE
all_pairs_equal(list(iris, iris, 2))
#> [1] FALSE
由 reprex package (v2.0.1)
于 2021-10-05 创建