Dcast功能 - >重新排序列

时间:2018-06-06 07:58:48

标签: r dplyr rows dcast

我使用dcast功能显示不同公司每月的支出。当然我想要1月1日,然后是2月等,而不是字母顺序。

Spendings <- data %>%
    filter(Familie == "Riegel" & Jahr == "2017") %>%
    group_by(Firma, Produktmarke, `Name Kurz`) %>%
    summarise(Spendingsges = sum(EUR, na.rm = TRUE))

Spendings <- dcast(data = Spendings, Firma + Produktmarke ~ `Name Kurz`, value.var="Spendingsges")
Spendings

                Firma               Produktmarke     Apr     Aug     Dez     Feb     Jan     Jul     Jun     Mai     Mrz     Nov     Okt     Sep
                Company1           Product1          228582 1902138  725781      NA  709970      NA  265313  228177      NA      NA 1463258 4031267

有没有办法重新排列字符串动态?例如,对于2018年,数据帧较短,因此我无法使用:

Spendings <- Spendings[,c("Firma", "Produktmarke", "Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")]

1 个答案:

答案 0 :(得分:0)

    Spendings_raw <- data.frame(matrix(ncol = 14, nrow = 0))
colnames(Spendings_raw) <- c("Firma", "Produktmarke", "Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
Spendings_raw

Spendings <- data %>%
    filter(Familie == "Riegel" & Jahr == "2017") %>%
    group_by(Firma, Produktmarke, `Name Kurz`) %>%
    summarise(Spendingsges = sum(EUR, na.rm = TRUE))


Spendings <- dcast(data = Spendings, Firma + Produktmarke ~ `Name Kurz`, value.var="Spendingsges")
Spendings <- rbind.fill(Spendings_raw, Spendings)

这完美无缺; - )。