【问题标题】:increase the number of defaulters in a sample增加样本中的违约者数量
【发布时间】:2014-05-02 11:45:26
【问题描述】:

我有一个银行数据集,其中有 5% 的违约者,其余的都很好(非违约者)。

我想创建一个有 30% 违约者和 70% 非违约者的样本。

假设我的数据集是数据,并且它有一个名为“默认”的列,表示 0 或 1,我如何获得具有 30% 默认值、70% 非默认值的样本,因为我的原始数据集只有 5% 的默认值。

谁能提供R代码。那太好了。 我尝试了以下方法来获得 100 个带有替换的随机样本

data[sample(1:nrow(data),size=100,replace=TRUE),]

但是我如何确保我得到的拆分是 30%,70%?

【问题讨论】:

    标签: r sample sampling


    【解决方案1】:

    sample 有一个选项prob,它表示一个概率权重向量,用于获取被采样向量的元素。所以你可以使用prob=c(0.3,0.7) 作为sample 的参数。

    例如

    sample(0:1, 100, replace=TRUE, prob=c(0.3,0.7))
    

    【讨论】:

      【解决方案2】:

      假设 df 是您的数据框,default 是指示谁默认的列。

      无需更换即可取样:

      df[c(sample(which(df$default),30), sample(which(!df$default),70)),]
      

      使用替换进行采样(即可能重复记录):

      df[c(sample(which(df$default),30,TRUE), sample(which(!df$default),70,TRUE)),]
      

      或者,如果您不想指定违约者和非违约者的确切数量,您可以为每行指定一个抽样概率:

      set.seed(1)
      df <- data.frame(default=rbinom(250,1,.5), y=rnorm(250))
      
      n <- 100 # could be any number, but closer you get to nrow(df) the less the weights matters
      s <- sample(seq_along(df$default), n, prob=ifelse(df$default, .3, .7))
      table(df$default[s])
      #
      #  0  1 
      # 61 39 
      
      n <- 150 # could be any number, but closer you get to nrow(df) the less the weights matters
      s <- sample(seq_along(df$default), n, prob=ifelse(df$default, .3, .7))
      table(df$default[s])
      #
      #  0  1 
      # 97 53
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-03
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        相关资源
        最近更新 更多