如何重新调整 tibble 中的一个因素
How to relevel a factor inside a tibble
我正在尝试更改以下小标题中因子字段等级的级别:
# 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")
但这会返回错误:
Error: f
must be a factor (or character vector or numeric vector).
这个字段是一个因素,我做错了什么?
尝试在内部升级 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"
我正在尝试更改以下小标题中因子字段等级的级别:
# 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")
但这会返回错误:
Error:
f
must be a factor (or character vector or numeric vector).
这个字段是一个因素,我做错了什么?
尝试在内部升级 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"