逻辑测试以确定 R 中分组数据框中是否存在某个值(整洁的解决方案)

发布于 2025-01-18 07:18:42 字数 485 浏览 4 评论 0原文

我想测试一个值是否存在于我按因子分组的大型数据框中的两个值之间。基本上,我有一列包含数值,我想测试是否有任何行的值在 -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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

記柔刀 2025-01-25 07:18:42

正如评论中指出的,您只需要使用 any 一次,不需要 ifelse 因为使用 any 已经返回逻辑值。

library(dplyr)

x <-
  tibble(value = c(-10, 8, 10, 0, 6, 10),
         group = c('A', 'A', 'A', 'B', 'B', 'B')) 

x %>%
  group_by(group) %>%
  mutate(logical_test = any(value >= -5 & value <= 5))

输出

  value group logical_test
  <dbl> <chr> <lgl>       
1   -10 A     FALSE       
2     8 A     FALSE       
3    10 A     FALSE       
4     0 B     TRUE        
5     6 B     TRUE        
6    10 B     TRUE  

或使用 data.table

library(data.table)

setDT(x)[, test := any(value >= -5 & value <= 5), by = group]

或使用基本 R:

x$logical_test <- as.logical(ave(x$value, x$group, FUN = \(x) any(x >= -5 & x <= 5)))

As pointed out in the comments, you only need to use any once and do not need ifelse as using any will already return a logical.

library(dplyr)

x <-
  tibble(value = c(-10, 8, 10, 0, 6, 10),
         group = c('A', 'A', 'A', 'B', 'B', 'B')) 

x %>%
  group_by(group) %>%
  mutate(logical_test = any(value >= -5 & value <= 5))

Output

  value group logical_test
  <dbl> <chr> <lgl>       
1   -10 A     FALSE       
2     8 A     FALSE       
3    10 A     FALSE       
4     0 B     TRUE        
5     6 B     TRUE        
6    10 B     TRUE  

Or with data.table:

library(data.table)

setDT(x)[, test := any(value >= -5 & value <= 5), by = group]

Or with base R:

x$logical_test <- as.logical(ave(x$value, x$group, FUN = \(x) any(x >= -5 & x <= 5)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文