如何知道数字是否在R中的确定间隔内

我有一个包含3列的数据集:默认,高度和重量。

我对变量进行了装箱并将其变绿(我必须这样做)在列表中。每个分箱都有一个问题,但现在我想根据我的观察结果在哪些数据桶中添加这些问题: 例如,数据框

df1 <- data.frame(default=sample(c(0,1),replace=TRUE,size=100,prob=c(0.9,0.1)),height=sample(150:180,100,replace=T),weight=sample(50:80,replace=T))
> head(df1)
#    default  height  weight
# 1       0    172     54
# 2       0    169     71
# 3       0    164     61
# 4       0    156     55
# 5       0    180     66
# 6       0    162     63

垃圾箱(我将显示第一个垃圾箱)

bins <- lapply(c("height","weight"),function(x) woe.binning(df1,"default",x,min.perc.total=0.05,min.perc.class=0.05,event.class=1,stop.limit = 0.05)[2])
# [[1]]
# [[1]][[1]]
#                woe cutpoints.final cutpoints.final[-1] iv.total.final  0 1 col.perc.a col.perc.b      iv.bins
# (-Inf,156] -46.58742            -Inf                 156      0.1050725 21 5 0.24137931 0.38461538 0.0667299967
# (156,168]   23.91074             156                 168      0.1050725 34 4 0.39080460 0.30769231 0.0198727638
# (168,169]  -10.91993             168                 169      0.1050725  6 1 0.06896552 0.07692308 0.0008689599
# (169,Inf]  25.85255             169                 Inf      0.1050725 26 3 0.29885057 0.23076923 0.0176007627
# Missing           NA             Inf             Missing      0.1050725  0 0 0.00000000 0.00000000           

现在我想在垃圾箱中看到的是我的数据。 我想要的输出与此类似

#    default  height  weight woe_height   woe_weight
# 1       0    160     54      23.91074   -8.180032
# 2       0    140     71     -46.58742   -7.640947 

有什么办法吗?我在这里看到的主要问题是间隔(a,b)为strings。我当时正在考虑使用substr()或类似的方法在逻辑选项中分隔字符串,但我认为这行不通,而且不太优雅。 任何帮助都将受到欢迎,在此先感谢。

tarenamis 回答:如何知道数字是否在R中的确定间隔内

这对您来说很好吗?

apply_woe_binning <- function(df,x){

  # woe binning
  w <- woe.binning(df,"default",x,min.perc.total=0.05,min.perc.class=0.05,event.class=1,stop.limit = 0.05)[[2]]

  # create new column name
  new_col <- paste("woe",sep = "_")

  # define cuts
  cuts <- cut(df[[x]],w$cutpoints.final)

  # add new column
  df[[new_col]] <- w[cuts,"woe",drop = TRUE]

  df
}

# one by one
df2 <- apply_woe_binning(df1,"height")
df2 <- apply_woe_binning(df2,"weight")


# in a functional
df2 <- Reduce(function(y,x) apply_woe_binning(df = y,x = x),c("height","weight"),init = df1)
本文链接:https://www.f2er.com/3028064.html

大家都在问