r - 在列表的两个元素中捕获不相等的值
问题描述
我想创建if()
条件来捕获x
a 元素中的值list()
不完全相同或y
a 元素中的值list()
不完全相同或两种情况一起出现的情况。
具体而言,我提供了 4 个列表以及下面的预期警告。
这在R中可能吗?
A = list(x = c(1,1,1,1), y = c(2,4,3,3)) # Expect warning that says `y` is bad!
B = list(x = c(1,2,1,1), y = c(3,3,3,3)) # Expect warning that says `x` is bad!
C = list(x = c(1,2,1,1), y = c(3,2,3,3)) # Expect warning that says `x` and `y` are bad!
D = list(x = c(1,1,1,1), y = c(3,3,3,3)) # Expect no warning !
解决方案
我们可以创建一个条件length
来unique
检查list
f1 <- function(lst_obj) {
v1 <- sapply(lst_obj, function(x) length(unique(x)))
i1 <- names(which(v1 != 1))
if(length(i1) == 1) {
warning(paste(i1, " is bad!"))
} else if(length(i1) > 1) {
warning(paste(i1, collapse = ' and '), " are bad!")
}
}
f1(A)
#Warning message:
#In f1(A) : y is bad!
f1(B)
#Warning message:
#In f1(B) : x is bad!
f1(C)
#Warning message:
#In f1(C) : x and y are bad!
f1(D)
推荐阅读
- html - 尽管没有填充,但 Div 空间
- python - 如何使用 Python 将新列附加到 csv?
- javascript - 追加来自多个表单的数据以将所有记录存储在 json 中
- shell - Shell Scripting - 列出目录中文件的标题行
- xpath - 计算包含两组 1 且由 0 分隔的列表中 1 的数量
- sql - 从具有两个父级的子表中删除,而无需在 sql server 中进行级联删除
- http - 如何处理通过 HTTP 上传的大文件而不将请求存储在临时文件中
- ios - 在哪些情况下需要使用 MTLStoreActionStoreAndMultisampleResolve 而不是 MTLStoreActionMultisampleResolve?
- ruby-on-rails - 让用户在 Rails 应用程序中下载 CSV 文件
- c++ - 使用指针迭代一系列原始类型声明?