【发布时间】:2021-05-19 23:10:59
【问题描述】:
假设,我有一个名为 iris 的数据集。我想在这个数据集中创建一个名为 sepal_length_group 的指标变量。该指标的值为 p25、p50、p75 和 p100。例如,如果物种是“setosa”并且Sepal.Length 等于或小于归类为“setosa”的所有物种的第 25 个百分位,我希望 sepal_length_group 等于“p25”进行观察。我编写了以下代码,但它会生成所有 NA:
library(skimr)
sepal_length_distribution <- iris %>% group_by(Species) %>% skim(Sepal.Length) %>% select(3, 9:12)
iris_2 <- iris %>% mutate(sepal_length_group = ifelse(Sepal.Length <= sepal_length_distribution[which(sepal_length_distribution$Species == "setosa"),2], "p25", NA))
iris_2 <- iris %>% mutate(sepal_length_group = ifelse(Sepal.Length > sepal_length_distribution[which(sepal_length_distribution$Species == "setosa"),2] &
Sepal.Length <= sepal_length_distribution[which(sepal_length_distribution$Species == "setosa"),3], "p50", NA))
iris_2 <- iris %>% mutate(sepal_length_group = ifelse(Sepal.Length > sepal_length_distribution[which(sepal_length_distribution$Species == "setosa"),3] &
Sepal.Length <= sepal_length_distribution[which(sepal_length_distribution$Species == "setosa"),4], "p75", NA))
iris_2 <- iris %>% mutate(sepal_length_group = ifelse(Sepal.Length > sepal_length_distribution[which(sepal_length_distribution$Species == "setosa"),4] &
Sepal.Length < sepal_length_distribution[which(sepal_length_distribution$Species == "setosa"),5], "p100", NA))
任何帮助将不胜感激!
【问题讨论】:
-
那么按组划分分位数?
-
所以您特别想使用skimr 输出?当您说指标变量时,您的意思是您基本上想要一个有序因子?
标签: r if-statement dplyr skimr