【问题标题】:Dplyr - create a new column "group of numbers with decimal"Dplyr - 创建一个新列“带小数的数字组”
【发布时间】:2018-12-11 20:58:27
【问题描述】:

我有一个数据框:Ratio2016

Name      Percapita
Alabama    0.60
Alaska     0.40
Arizona    0.22
California 1.53

要创建基于 Percapita 列颜色的传单地图,我想创建一个新列 percent_group 0.05-0.1 0.1-0.5 0.5-1.0 1.0-1.5

我的代码: `

ratio2016<- ratio2016 %>% 
   mutate(percent_group = case_when(
    percapita %in% 0.05:0.1 ~ 0.05-0.1,
    percapita %in% 0.1:0.5 ~ 0.1-0.5,
    percapita %in% 0.5:1.0 ~ 0.5-1.0,
    percapita %in% 1.0:1.5 ~ 1.0-1.5,
    percapita %in% 1.5:2.0 ~ 1.5-2.0))

我得到一个只有“NA”的列 我有 2 行与 Nas。

我的错误在哪里? 谢谢大家!

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    %in% 是检查一个值是否是集合的成员,所以在这里使用是错误的。你需要between()

    ratio2016 <- ratio2016 %>% 
      mutate(percent_group = case_when(
        between(percapita, 0.05, 0.1) ~ "0.05-0.1",
        between(percapita, 0.1, 0.5) ~ "0.1-0.5",
        between(percapita, 0.5, 1) ~ "0.5-1.0",
        between(percapita, 1, 1.5) ~ "1.0-1.5",
        between(percapita, 1.5, 2) ~ "1.5-2.0"))
    

    这将为您提供您的专栏。

    顺便说一句,您可以使用 cut() 以更少的代码完成它:

    ratio2016 %>% mutate(percent_group =
        cut(percapita, c(0.05, 0.1, 0.5, 1, 1.5, 2), 
        labels = c("0.05-0.1","0.1-0.5", "0.5-1.0", "1.0-1.5", "1.5-2.0"))
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-04
      • 2018-09-26
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      相关资源
      最近更新 更多