通过 R 中的另一个对象变量对变量重新排序

Reorder a variable by another object variable in R

我有一个 DF 并且想修改 y 轴,通过来自另一个对象的变量对我的数据进行排序。我尝试使用 forcats 中的 fct_reorder,但没用。

我的代码:

library(tidyverse)
library(ggridges)
library(zoo)

url <- httr::GET("https://xx9p7hp1p7.execute-api.us-east-1.amazonaws.com/prod/PortalGeral",
                 httr::add_headers("X-Parse-Application-Id" =
                                       "unAFkcaNDeXajurGB7LChj8SgQYS2ptm")) %>%
    httr::content() %>%
    '[['("results") %>%
    '[['(1) %>%
    '[['("arquivo") %>%
    '[['("url")

data <- openxlsx::read.xlsx(url) %>%
    filter(is.na(municipio), is.na(codmun)) %>%
    mutate_at(vars(contains(c("Acumulado", "Novos", "novos"))), ~ as.numeric(.))

data[,8] <- openxlsx::convertToDate(data[,8])

bigger_state <- data %>%
    group_by(estado) %>%
    mutate(diasposdez = 1:n(),
           mm7d = rollmean(casosNovos, 7, fill = NA, allign = "right")) %>%
    filter(data == data[which.max(mm7d)], !is.na(estado)) %>%
    arrange(desc(casosNovos)) %>%
    pull(estado)
         
data %>%
    group_by(estado) %>%
    mutate(height = rollmean(casosNovos, k = 7, align = "right", fill = NA) / sum(casosNovos),
           estado = as_factor(estado)) %>%
    filter(data >= "2020-05-01") %>%
    ggplot(aes(x = data, y = fct_reorder(.f = estado, .x = bigger_state), height = scales::rescale(height))) +
    geom_ridgeline() +
    scale_x_date(date_breaks = "2 weeks",
                 date_labels = "%d/%b/%Y")

错误:

Error in fct_reorder(.f = estado, .x = bigger_state) : 
  length(f) == length(.x) is not TRUE

只需使用 factor(estado, bigger_state) 而不是 fct_reorder(.f = estado, .x = bigger_state)。您正试图将所有值与因子水平匹配,这给了您错误。