如何在小标题中重新调整因素

时间:2019-07-25 10:41:08

标签: r dataframe dplyr forcats

我尝试通过以下方式更改因子字段“等级”的水平:

# A tibble: 10 x 8
      id destination package_type  `7_day_price` `14_day_price` for_families for_groups Grade
   <dbl> <chr>       <chr>                 <dbl>          <dbl>        <dbl>      <dbl> <fct>
 1     1 Aruba       all inclusive          1200           2000            1          1 A    
 2     2 Bora bora   flight only            1400           2333            1          0 B    
 3     3 Wales       flight only             125            210            1          1 D    
 4     4 Cancun      flight only            1600           2750            1          1 B    
 5     5 Antigua     all inclusive          2100           3500            0          1 A    
 6     6 Mustique    half board             7599          12670            0          0 A    
 7     7 Tobago      half board             2459           4010            1          1 B    
 8     8 Jamaica     all inclusive          1850           3090            0          1 C    
 9     9 St Lucia    all inclusive          1800           3000            1          0 B    
10    10 Guadeloupe  all inclusive          1750           2900            1          1 C   

我正在使用代码进行此操作:

library(tidyverse)
df %>% fct_relevel(df['Grade'],"A","B","C","D")

但这会返回错误:

  

错误:f必须是一个因子(或字符向量或数字向量)。

此字段是一个因素,我在做什么错了?

1 个答案:

答案 0 :(得分:0)

尝试在mutate内部进行重新调整:

df %>%
  mutate(Grade = fct_relevel(Grade, "A","B","C","D"))

这是一个简单的玩具示例:

df <- tibble(Grade = factor(LETTERS[1:4]))

pull(df, Grade) %>% levels()
[1] "A" "B" "C" "D"

df %>% mutate(Grade = fct_relevel(Grade, "B", "C", "A", "D")) %>% pull(Grade) %>% levels()
[1] "B" "C" "A" "D"