R中欠采样的最佳方法是什么

What is the best way of Under sampling in R

我有一个具有属性 A、B、C 的数据集。C 是一个具有 2 个标签 zz 和 z 的因子。 number of (z) > number of (zz),我想下采样 我的数据集,以便在新数据中具有相同的 zz 和 z 值。 不能为此使用任何外部包最好使用 sample 函数

--------------------------------------------------
| Attribute A   |   Attribute B . | Attribute c  |
--------------------------------------------------
|  xx           | y1              | zz           |
--------------------------------------------------
|  mm           | r1              |  z           |
--------------------------------------------------
|  ab           | 1r              |  z           |
--------------------------------------------------
|  ry           | cm              |  zz          |
--------------------------------------------------
|  ca           | rx              |  z           |
--------------------------------------------------
|  mm           | zr              |  z           |
--------------------------------------------------

结果应该是-


| Attribute A   |   Attribute B . | Attribute c  |
--------------------------------------------------
|  xx           | y1              | zz           |
--------------------------------------------------
|  mm           | r1              |  z           |
--------------------------------------------------
|  ab           | 1r              |  z           |
--------------------------------------------------
|  ry           | cm              |  zz          |
--------------------------------------------------

这里zz的概率=z的概率=0.5

假设您的数据位于名为 data 的数据框中,其中包含列 ABC,您可以执行以下操作:

## rows that have "z" and "zz" entries
z_ind <- which(data$C == "z")
zz_ind <- which(data$C == "zz")

nsamp <- 10   #number of elements to sample
## if you want all elements of the smaller class, could be:
## nsamp <- min(length(z_ind), length(zz_ind))

## select `nsamp` entries with "z" and `nsamp` entries with "zz"
pick_z <- sample(z_ind, nsamp)
pick_zz <- sample(zz_ind, nsamp)

new_data <- data[c(pick_z, pick_zz), ]