【问题标题】:Categorize a continuous variable based on groups of n in R [duplicate]根据 R 中的 n 组对连续变量进行分类
【发布时间】:2020-09-04 16:14:31
【问题描述】:

我有以下数据:

library(dplyr, warn.conflicts = FALSE)

df <- tibble(
  x = c(0, 2, 6, 9, 10, 13, 14, 17, 20, 21, 24, 28, 29),
  y = rnorm(13)
)

df
#> # A tibble: 13 x 2
#>        x       y
#>    <dbl>   <dbl>
#>  1     0 -1.54  
#>  2     2 -0.244 
#>  3     6  0.796 
#>  4     9 -0.444 
#>  5    10  0.0147
#>  6    13  0.163 
#>  7    14  0.617 
#>  8    17  0.942 
#>  9    20 -0.755 
#> 10    21  0.384 
#> 11    24 -0.657 
#> 12    28 -1.02  
#> 13    29  0.387

我想根据x 列中的组创建一个新列。假设x 列在 内。此变量x10 秒 获得一个新分类。所以,换句话说,当x09之间时,它被归类为step_1,以此类推……

我一直在寻找一种有效的方法。当然,我的真实示例要复杂得多,我无法对其进行硬编码。以下是我想要的输出:

#> # A tibble: 13 x 3
#>        x       y z     
#>    <dbl>   <dbl> <chr> 
#>  1     0 -0.700  step_1
#>  2     2 -0.177  step_1
#>  3     6  0.238  step_1
#>  4     9  1.91   step_1
#>  5    10  0.914  step_2
#>  6    13  1.37   step_2
#>  7    14  1.82   step_2
#>  8    17  0.547  step_2
#>  9    20  0.0324 step_3
#> 10    21  0.0275 step_3
#> 11    24  0.677  step_3
#> 12    28 -0.583  step_3
#> 13    29 -1.39   step_3

有什么想法吗?

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    您可以使用整数除法运算符%/% 来获得将 x 除以 10 的整数部分,然后将其加 1。这将为您提供正确的步骤编号。将此添加到 paste0 调用中以将 "step_" 粘贴到前面,您就搞定了:

    df %>% mutate(z = paste0("step_", (x %/% 10 + 1)))
    #> # A tibble: 13 x 3
    #>        x       y z     
    #>    <dbl>   <dbl> <chr> 
    #>  1     0  0.595  step_1
    #>  2     2  1.44   step_1
    #>  3     6 -0.375  step_1
    #>  4     9 -0.808  step_1
    #>  5    10 -0.298  step_2
    #>  6    13 -0.774  step_2
    #>  7    14 -0.769  step_2
    #>  8    17  0.335  step_2
    #>  9    20  0.696  step_3
    #> 10    21  0.284  step_3
    #> 11    24 -0.568  step_3
    #> 12    28 -0.0942 step_3
    #> 13    29 -0.547  step_3
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-03
      • 2021-12-01
      • 1970-01-01
      • 2021-09-26
      • 2017-09-09
      • 2021-12-05
      • 2017-03-15
      • 2019-12-28
      相关资源
      最近更新 更多