【问题标题】:R logical issue: longer object length is not a multiple of shorter object length ( dplyr::if_else() )R逻辑问题:较长的对象长度不是较短对象长度的倍数( dplyr::if_else() )
【发布时间】:2020-09-09 22:54:18
【问题描述】:

我不确定如何使用 if_else() 以外的其他方法修改我的代码并保持其效率。这是我原始代码的一个简单示例:

library(dplyr)

# The goal is to know between which threshold belongs each record
data <- c(runif(99999), NA)
threshold <- seq(0, 1, by=0.1)
rank <- if_else(is.na(data), NA, max(which(data >= threshold))) # Error: longer object length is not a multiple of shorter object length

谢谢你

【问题讨论】:

  • datathreshold 需要具有相同的长度才能比较它们。您想在这里实现什么目标?

标签: r performance if-statement dplyr logical-or


【解决方案1】:

我认为if_else 在这里不是正确的功能。尝试使用findIntervalcut,这将找到您的data 所在的threshold 的正确存储桶。

findInterval(data, threshold)

cut

cut(data, threshold)

如果您想获得threshold 索引,请使用cutlabels = FALSE

cut(data, threshold, labels = FALSE)

【讨论】:

  • 感谢您的帮助。你是对的,我使用了你的第一个解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2020-07-15
  • 1970-01-01
相关资源
最近更新 更多