0
votes

I've got Crosstable in which there is a vector of counts with matched factors as seen below.

I'd like make a plot of factors "0-7" "11-13.5" "13.5+" "7-9" ... with counts, but in a specific order like 0-7 first, then 7-9, 11-13.5 and so on...

How could this be done in a fast manner?

> str(data2)
List of 4
 $ t       : int [1, 1:6] 3342 6954 6002 5150 4868 2776
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr [1:6] "0-7" "11-13.5" "13.5+" "7-9" ...
1

1 Answers

0
votes

Consider using the Recoding addins from the questionr package.

You can relabel using the level function:

## Reordering df1$bands
df1$bands <- factor(df1$bands, levels=c("0-7", "7-9", "11-13.5", "13.5+"))

Build labels:

df1 <- df %>% mutate(bands = case_when(value <= 7 ~ "0-7",
                                value <= 9 ~ "7-9",
                                value <= 13.5 ~ "11-13.5",
                                value > 13.5 ~ "13.5+" )) 

Here's the data sorted:

df1 %>% count(bands)

# A tibble: 4 x 2
  bands       n
  <fct>   <int>
1 0-7         7
2 7-9         2
3 11-13.5     5
4 13.5+       7

Sample Data:

df <- tibble::tribble(
  ~t, ~value,
   1,    0.5,
   3,    1.5,
   5,    2.5,
   7,    3.5,
   9,    4.5,
  11,    5.5,
  13,    6.5,
  15,    7.5,
  17,    8.5,
  19,    9.5,
  21,   10.5,
  23,   11.5,
  25,   12.5,
  27,   13.5,
  29,   14.5,
  31,   15.5,
  33,   16.5,
  35,   17.5,
  37,   18.5,
  39,   19.5,
  41,   20.5
  )