Pivot_longer 错误(由于 类 不同无法合并)

Pivot_longer error (cannot combine due to different classes)

我想用以下数据集绘制条形图。 X 轴为 'Input' 类型和 'Rtype'

df <- read.table(text = "       Input Rtype Rcost Rsolutions  Btime Bcost 
1   12-proc.     typea    36     614425     40    36 
2   15-proc.     typeb    51     534037     50    51 
3    18-proc     typec    62    1843820     66    66 
4    20-proc     typea    68    1645581 104400    73 
5 20-proc(l)     typeb    64    1658509  14400    65 
6    21-proc     typec    78    3923623 453600    82", 
header = TRUE,sep = "")

dfm <- pivot_longer(df, -Input, names_to="variable", values_to="value")

Image of dataset

但是,我收到此错误:错误:无法组合 Input Rtype .

请指教,谢谢!

也许这会有所帮助:

library(tidyverse)

df <- read.table(text = "       Input Rtype Rcost Rsolutions  Btime Bcost 
1   12-proc.     typea    36     614425     40    36 
2   15-proc.     typeb    51     534037     50    51 
3    18-proc     typec    62    1843820     66    66 
4    20-proc     typea    68    1645581 104400    73 
5 20-proc(l)     typeb    64    1658509  14400    65 
6    21-proc     typec    78    3923623 453600    82", 
header = TRUE,sep = "")

dfm <- pivot_longer(df, -c(Input, Rtype), names_to="variable", values_to="value")
dfm
#> # A tibble: 24 × 4
#>    Input    Rtype variable     value
#>    <chr>    <chr> <chr>        <int>
#>  1 12-proc. typea Rcost           36
#>  2 12-proc. typea Rsolutions  614425
#>  3 12-proc. typea Btime           40
#>  4 12-proc. typea Bcost           36
#>  5 15-proc. typeb Rcost           51
#>  6 15-proc. typeb Rsolutions  534037
#>  7 15-proc. typeb Btime           50
#>  8 15-proc. typeb Bcost           51
#>  9 18-proc  typec Rcost           62
#> 10 18-proc  typec Rsolutions 1843820
#> # … with 14 more rows

# If you have all 18 factor levels in your data:
ggplot(dfm, aes(x = interaction(Input, Rtype, sep = " "),
                y = value, fill = variable)) +
  geom_bar(stat = "identity") +
  scale_y_log10(labels = scales::dollar,
                name = "log10(cost)") +
  scale_fill_viridis_d(end = 0.8) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle = 90, vjust = 0.5))

# If you don't have all 18 factor levels in your data:
all_combinations <- expand_grid(Input = dfm$Input,
                                Rtype = dfm$Rtype) %>%
  distinct()

dfm_expanded <- left_join(all_combinations, dfm) %>%
  replace_na(list("0"))
#> Joining, by = c("Input", "Rtype")

ggplot(dfm_expanded, aes(x = interaction(Input, Rtype, sep = " "),
                         y = value, fill = variable)) +
  geom_bar(stat = "identity") +
  scale_y_log10(labels = scales::dollar,
                name = "log10(cost)") +
  scale_fill_viridis_d(end = 0.8) +
  theme(axis.title.x = element_blank(),
        axis.text.x = element_text(angle = 90, vjust = 0.5))
#> Warning: Removed 12 rows containing missing values (position_stack).

reprex package (v2.0.1)

于 2022-04-04 创建