如何首先转置矩阵,然后用0填充缺失月份的值

时间:2018-11-23 09:43:24

标签: r matrix

我对R中的矩阵结构操作有疑问,如何首先转置矩阵,然后用0填充缺失月份的值。 例如,我有一个水果店的数据,其中每个月销售的苹果和橙子的数量如下,该数字应为数字。

fruit   Month   amount
apple   1   243
apple   7   66
apple   8   22
orange  2   89
orange  5   12

但是,我想转置Ma并将缺少的月份的苹果和橙子的数量设置为0,如下所示,您能帮忙吗?

Month   1   2   3   4   5   6   7   8   9   10  11  12
apple   243 0   0   0   0   0   66  22  0   0   0   0
orange  0   89  0   0   12  0   0   0   0   0   0   0

1 个答案:

答案 0 :(得分:0)

library(reshape2)
library(tidyverse)
data <- data.frame(Ma[-1,],stringsAsFactors = F); names(data) <- Ma[1,]
data <- data %>% mutate(Month = as.numeric(Month),amount = as.numeric(amount)) %>%
  complete(Month = 1:12,fill= list(amount = 0)) %>% 
  dcast(Month~fruit, value.var = 'amount',fill = 0) %>% select(Month, apple, orange) %>% t()

首先安装库:

install.packages(c('tidyverse','rechape2'))