首页 > 解决方案 > 你可以在 R 的 case_when 语句中使用 for 循环吗?

问题描述

我正在尝试在 R 中编写一个函数,该函数聚合按 N 个价格桶分组的数据,其中 N 是该函数的输入变量。

priceDiffBucket <- function(prices,numBuckets){
  vec <- c(0:numBuckets)
#Create N (numBuckets) buckets where the min/max are rounded off to the lowest/highest 5th integer
  bucketborders <- quantile(c((min(prices)-min(prices)%%5):
                                (max(prices) - max(prices)%%5+5)),probs = vec/numBuckets)
#Create a dataframe which contains these buckets as a column
  dfFinal <- case_when(
    for (i in 1:(length(vec)-1)){
      prices < bucketborders[i+1] ~ paste(paste0('"',bucketborders[i]),"-",
                                          paste0('"',bucketborders[i+1],'"'))
    }
  )
  return(dfFinal)
}

在此之后,我将根据这些存储桶汇总值。但是 R 似乎不接受 case_when() 语句中的 for 语句,因此我无法在通用函数中实现这些存储桶。我收到以下错误:

 Error: No cases provided.
Run `rlang::last_error()` to see where the error occurred. 

运行 Rlang::lst_error() 只会显示最后一段代码,但对我没有帮助。如果 case-when 语句中的 for 循环是不可能的,那么我试图在 R 中以另一种方式做的事情是可能的吗?

标签: rfor-loopcase-when

解决方案


我无法完全解释您要做什么。但该cut功能是一种生成“桶”的方法,例如:

x <- sample(1:100)
breaks <- c(-Inf, 25, 50, Inf)
labels <- c('lo', 'med', 'high')
buckets <- cut(x, breaks = breaks, labels = labels)

cbind然后,您可以将buckets向量添加到prices向量或数据框。


推荐阅读