我有幾個單位的協變數資料。此外,我可以訪問根據分數對我的觀察結果進行排名的評分規則。
我決定X根據 的分位數劃分訓練樣本score,這是通過使用包中的quantile_group函式實作的GenericMl。
## Generate data.
set.seed(1986)
n <- 1000
n_val <- 10000
k <- 3
X <- matrix(rnorm(n * k), ncol = k)
X_val <- matrix(rnorm(n_val * k), ncol = k)
score <- rexp(n)
score_val <- rexp(n_val)
## Quantiles of score.
library(GenericML)
groups <- quantile_group(score)
head(groups)
#> [-Inf, 0.277) [0.277, 0.678) [0.678, 1.34) [1.34, Inf]
#> [1,] TRUE FALSE FALSE FALSE
#> [2,] FALSE FALSE FALSE TRUE
#> [3,] FALSE FALSE TRUE FALSE
#> [4,] FALSE TRUE FALSE FALSE
#> [5,] FALSE TRUE FALSE FALSE
#> [6,] FALSE FALSE TRUE FALSE
的第g列groups由TRUEs 和FALSEs 組成,表示 的第g個分位數score。我的下一步是X_val使用相同的磁區劃分驗證樣本中的單元groups。為了澄清,我想分為score_val由給出的間隔定義的四組colnames(groups):
colnames(groups)
#> [1] "[-Inf, 0.277)" "[0.277, 0.678)" "[0.678, 1.34)" "[1.34, Inf]"
我需要自動化這個。
uj5u.com熱心網友回復:
我認為這可能是一種獲得您正在尋找的東西的方法。我不使用GenericML包,因為如果我理解得很好,你只想X_val分成子集。
# Load library
library(dplyr)
# Generate data
set.seed(1986)
n <- 1000
n_val <- 10000
k <- 3
X <- matrix(rnorm(n * k), ncol = k)
# Here I use "as.data.frame.matrx" in order to add the group (according to the interval)
X_val <- as.data.frame.matrix(matrix(rnorm(n_val * k), ncol = k))
score <- rexp(n)
score_val <- rexp(n_val)
# Get the quantiles of score
q.score <- quantile(score)
# Divide score_val acording to the quantiles of q.score
group.var <- cut(score_val, breaks = c(-Inf, q.score[2:4], Inf))
# Add "group.var" to X_val matrix
X_val$group.var <- group.var
# Divide the information according to "group.var"
new_X_val <- X_val %>%
group_split(group.var)
最后,你得到的是new_X_val一個包含 4 個元素的串列,每個元素一個分位數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529435.html
標籤:r
上一篇:將列除以參考行
下一篇:用對應的代碼R替換部分字串
