0

I have the following data:

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

And I would like to create a new column based on groups from the x column. Let's imagine that column x is in seconds. This variable x gets a new classification every 10 seconds. So, in other words, when x is between 0 and 9, it is classified as step_1, and so on...

I was looking for an efficient way of doing it. Of course, my real example is much more complex and I can't hard code it. The following is my desired output:

#> # 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

Any ideas?

FMM
  • 1,857
  • 1
  • 15
  • 38

1 Answers1

2

You can use the integer division operator %/% to get the whole number part of dividing x by 10, then add 1 to it. This will give you the correct step number. Add this into a paste0 call to glue "step_" onto the front and you've got it:

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

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87