如何使用fct_relevel函数重新调整因子列?

时间:2018-09-30 10:12:05

标签: r dplyr categorical-data forcats

我是一个绝对的初学者,而且确实很挣扎-有人可以帮忙告诉我为什么收到该错误消息以及如何解决该错误消息吗?

这是我想要做的: enter image description here

这是我的数据:

use mysql;

1 个答案:

答案 0 :(得分:0)

要使用fct_relevel包的forcats函数来更改因子列中的级别,需要使用以下命令将wide formate data.frame转换为narrow format 例如melt软件包的reshape2功能。

请参见下面的代码:

df <- structure(list(Location = structure(c(3L, 1L, 4L, 2L), .Label = c("PC_infested", 
"PC_normal_mites", "PC_recapped", "PC_recapped_and_infested"), class = "factor"), 
    S1 = c(7.31, 3.2, 85.71, 85.71), S2 = c(7.46, 2.63, 83.33, 
    100), S3 = c(12.17, 11.3, 30.77, 69.23), S4 = c(10.77, 5.72, 
    82.35, 76.47), C1 = c(6.59, 0, 0, 0), C2 = c(15.94, 0, 0, 
    0), TS3 = c(14.97, 16.77, 25, 39.29)), class = "data.frame", row.names = c(NA, 
-4L))

library(reshape2)
library(forcats)

res <- df %>% melt(id = "Location") %>% rename(c("variable" = "type")) %>%
  mutate(type = fct_relevel(type, c("S1", "S2", "S3", "S4", "C1", "C2", "TS3")))

res$type

输出:

 [1] S1  S1  S1  S1  S2  S2  S2  S2  S3  S3  S3  S3  S4  S4  S4  S4  C1  C1  C1  C1  C2  C2  C2  C2  TS3 TS3 TS3 TS3
Levels: S1 S2 S3 S4 C1 C2 TS3