如何在R中使用另一个变量的分位数创建一个变量?

Gui*_*nca 3 r quantile dataframe dplyr

我正在尝试使用“dplyr”命令 mutate 创建一个变量,该变量必须指示另一个变量的分位数。

例如:

# 1.  Fake data:
data <- data.frame(
  "id" = seq(1:20),
  "score" = round(rnorm(20,30,20)))

# 2. Creating varaible 'Quantile_5'
data <-data %>% 
  mutate(Quntile_5 = ????)
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经创建了一个函数,该函数可以识别并返回分位数作为一个因子,并且该函数实际上有效

# 3. Create a function:
quantile5 <- function(x){
  x = ifelse(
    x < quantile(x,0.2),1,
    ifelse(x >= quantile(x,0.2) & x < quantile(x,0.4),2,
           ifelse(x >= quantile(x,0.4) & x < quantile(x,0.6),3,
                  ifelse(x >= quantile(x,0.6) & x < quantile(x,0.8),4,5
                         ))))
  return(as.factor(x))
}

# 4. Running the code:
data <-data %>% 
  mutate(Quntile_5 = quantile5(score))

# 5. Result:
data

   id score Quntile_5
1   1    55         5
2   2    56         5
3   3    26         3
4   4    42         3
5   5    41         3
6   6    26         3
7   7    57         5
8   8    12         1
9   9    21         2
10 10    25         2
11 11    37         3
12 12    18         2
13 13    54         5
14 14    47         4
15 15    52         4
16 16    -4         1
17 17    53         4
18 18    51         4
19 19    -7         1
20 20    -2         1
Run Code Online (Sandbox Code Playgroud)

但是,如果我想创建一个变量“Quantile_100”作为一个因子,指示每个观察值在 1 到 100 的哪个位置(在较大数据集的背景下),这不是一个很好的解决方案。有没有更简单的方法来创建这些五分位变量?

Ron*_*hah 5

这里有两个选项cut

1.

library(dplyr)

data %>% mutate(quantile100 = cut(score, 100, label = FALSE))
Run Code Online (Sandbox Code Playgroud)
#This is similar to @Anoushiravan R `findInterval` function.
data %>% 
    mutate(quantile100 = cut(score, unique(quantile(score, seq(0, 1, 0.01))), labels = FALSE))
Run Code Online (Sandbox Code Playgroud)