r - 你可以在 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 中以另一种方式做的事情是可能的吗?
解决方案
我无法完全解释您要做什么。但该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
向量或数据框。
推荐阅读
- mongodb - 基于属性值在 MongoDB 中聚合数据
- node.js - 从实时数据库获取 json 数据到 Dialogflow 内联编辑器(谷歌助手)
- sql - 有没有一种方法可以在 Google Spanner 中从两个不同的数据库中查询两个表?
- c# - 无法访问存储帐户 blob 获取 BlobContainerValidationError 错误 c#
- ruby - 如何检查 gem 的兼容 Ruby 版本
- c# - WPF DataGrid 在另一个 DataGrid 中的选定行上可见
- python - 获取 groupon 的访问令牌
- mysql - SQL 比较列在过去 X 小时内的更改
- java - 例外。我该如何解决?第一步
- php - 无法使用 phpMyAdmin 连接到 mySQL 服务器中的数据库