【问题标题】:How to create an inclusive binning function in R?如何在 R 中创建包容性分箱函数?
【发布时间】:2018-08-29 04:30:25
【问题描述】:

我正在尝试创建一个基于多个条件对数据进行分箱的函数。我的数据有两个变量:max_distactivated.

该函数应该为不同的 bin 创建多个向量;检查max_dist 是否在特定范围内,然后将1 附加到向量,如果它在范围内,activatedTRUE,如果activated 是@987654332,则将0 附加到列表中@。

关键部分是,对于每个观察,如果 max_dist 大于指定范围但activated 也是TRUE,那么我想在那个 bin 中包含一个 0。所以一些观察值高 @987654335 @ 值将被分箱多次。

目前我的结构是这样的(缩短版 - 全长有 6 个箱子):

binning_function <- function(df) {
 #create a series of vectors corresponding to bins
  two_hundred <- c()
  four_hundred <- c()

  #iterate through dataframe to add 0 or 1 values to each vector
  for (i in 1:nrow(df)) {
    if (df$activated[i]==TRUE && df$max_dist[i]<=0.2) {
        append(two_hundred, 1)
      }
    else if (df$max_dist[i]>0.2 || df$activated[i]==FALSE) {
        append(two_hundred, 0)
      }
   }

  for (i in 1:nrow(df)) {
    if (df$activated[i]==TRUE && df$max_dist[i]>0.2 && df$max_dist[i]<=0.4) {
        append(four_hundred, 1)
      }
    else if (df$max_dist[i]>0.4 || df$activated[i]==FALSE) {
        append(four_hundred, 0)
      }
  }

return(list(two_hundred,four_hundred))

}

当我在数据帧上运行此函数时,它会返回一个列表:

[[1]]
NULL

[[2]]
NULL

【问题讨论】:

标签: r function for-loop rstudio binning


【解决方案1】:

下面的解决方案使用apply() 一次对整个数据框执行操作。这也意味着您不必提前启动一个空向量。 它还使用ifelse() 来缩短长的if() {} else {} 语句:

data <- data.frame(row.names = paste0('s',1:100))
 data$max_dist <- runif(100,0,1)
 data$activated <- sample(c(T,F),100,replace=T)

 binning_function <- function(df) {
  two_hundred <- apply(df,1,function(x) {ifelse(x['max_dist']<=0.2 & x['activated'],1,0)})
  four_hundred <- apply(df,1,function(x) {ifelse(x['max_dist']<=0.4 & x['max_dist']>0.2 & x['activated'],1,0)})
  return(list(two_hundred, four_hundred))
}

 binning_function(df=data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    相关资源
    最近更新 更多