我打算使用“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 = ????)
到目前为止,我已经创建了一个函数来识别并返回分位数作为一个因子,并且它确实有效
# 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
但是,如果我想创建一个变量“Quantile_100”作为一个因子,指示每个观察值在 1 到 100 之间的哪个位置(在较大数据集的上下文中),这不是一个很好的解决方案。有没有更简单的方法来创建这些五分位数变量?
最佳答案
这里有两个带有 cut
的选项:
1.
library(dplyr)
data %>% mutate(quantile100 = cut(score, 100, label = FALSE))
#This is similar to @Anoushiravan R `findInterval` function.
data %>%
mutate(quantile100 = cut(score, unique(quantile(score, seq(0, 1, 0.01))), labels = FALSE))
关于r - 如何用 R 中另一个变量的分位数创建一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67258254/