2

我正在尝试在以下小标题中更改因子字段 Grade 的级别:

# 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必须是一个因子(或字符向量或数值向量)。

这个领域是一个因素,我做错了什么?

4

1 回答 1

2

尝试重新调整内部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"
于 2019-07-25T10:44:56.530 回答