首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >根据一个数据框中的值在另一个数据框中创建指示符变量

根据一个数据框中的值在另一个数据框中创建指示符变量
EN

Stack Overflow用户
提问于 2021-05-20 07:10:59
回答 1查看 36关注 0票数 1

假设我有一个名为iris的数据集。我想在这个数据集中创建一个名为sepal_length_group的指示器变量。此指示器的值为p25、p50、p75和p100。例如,对于一个观察,如果物种是"setosa“,并且如果所有被归类为"setosa”的物种的Sepal.Length等于或小于第25个百分位数,我希望sepal_length_group等于"p25“。我写了以下代码,但它会生成所有NAs:

代码语言:javascript
运行
复制
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))

任何帮助我们都将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-20 07:46:35

这可以通过使用@Camille注释的函数cut来简单地完成

代码语言:javascript
运行
复制
library(tidyverse)
iris %>%
  group_by(Species) %>%
  mutate(cat = cut(Sepal.Length, 
                   quantile(Sepal.Length, c(0,.25,.5,.75, 1)),
                   paste0('p', c(25,50, 75, 100)), include.lowest = TRUE))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67612049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档