逻辑测试以确定 R 中分组数据框中是否存在某个值(整洁的解决方案)
我想测试一个值是否存在于我按因子分组的大型数据框中的两个值之间。基本上,我有一列包含数值,我想测试是否有任何行的值在 -5 到 5 之间。下面是一个示例:
x <- tibble(value = c(-10, 8, 10, 0, 6, 10), group = c('A', 'A', 'A', 'B', 'B', 'B')) %>%
group_by(group) %>%
mutate(
logical_test = if_else(any(value >= -5) & any(value <= 5), TRUE, FALSE)
)
Group A
应该是 FALSE
。它的值不介于 -5 和 5 之间;然而,测试显示TRUE
。我不确定我做错了什么。 any()
这里的函数不是正确的吗?
非常感谢任何帮助。
I would like to test if a value exists between two values in a large dataframe that I've grouped by a factor. Basically, I have a column with numerical values and I'd like to test if any rows have a value between -5 and 5. Here's an example:
x <- tibble(value = c(-10, 8, 10, 0, 6, 10), group = c('A', 'A', 'A', 'B', 'B', 'B')) %>%
group_by(group) %>%
mutate(
logical_test = if_else(any(value >= -5) & any(value <= 5), TRUE, FALSE)
)
Group A
should be FALSE
. It does not have a value between -5 and 5; however, the test shows TRUE
. I'm unsure what I'm doing wrong. Is any()
not the correct function here?
Any assistance is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如评论中指出的,您只需要使用
any
一次,不需要ifelse
因为使用any
已经返回逻辑值。输出
或使用
data.table
:或使用基本 R:
As pointed out in the comments, you only need to use
any
once and do not needifelse
as usingany
will already return a logical.Output
Or with
data.table
:Or with base R: