从CrossTable中选择名称

时间:2019-04-16 18:39:34

标签: r

我有Crosstable,其中有一个向量与匹配因子相匹配,如下所示。

我想对因子“ 0-7”,“ 11-13.5”,“ 13.5 +”,“ 7-9” ...进行计数,但要按特定的顺序,如0-7,然后是7 -9、11-13.5等...

如何快速完成此操作?

> 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 个答案:

答案 0 :(得分:0)

考虑使用questionr包中的Recoding addins

您可以使用level函数重新标记:

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

构建标签:

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+" )) 

这里是排序的数据:

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

样本数据:

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
  )