2017-02-20 38 views
2

如何在R中的范围上投射聚合值并用零填充缺失的范围值。如何在R中的范围上投射聚合值并用零填充缺失的范围值

df <- data.frame (year = sample(c(2014:2016), 100, replace=T), 
        month = sample(c(1:5,8:12), 100, replace=T), 
        int = 1) 

# install.packages("reshape") 
library(reshape) 
month <- cast(df, year ~ month, sum, value = 'int') 
month 

输出:

# output 
    year 1 2 3 4 5 8 9 10 11 12 
1 2014 6 5 4 3 4 4 3 3 9 2 
2 2015 4 9 1 3 1 4 3 3 2 3 
3 2016 0 3 3 4 4 1 4 1 3 1 

如何设置缺少个月零?结果应该是这样的:

# output 
    year 1 2 3 4 5 >6< >7< 8 9 10 11 12 
1 2014 6 5 4 3 4 0 0 4 3 3 9 2 
2 2015 4 9 1 3 1 0 0 4 3 3 2 3 
3 2016 0 3 3 4 4 0 0 1 4 1 3 1 

有没有办法通过强制转换功能来做到这一点?

回答

2

我们可以使用tidyverse到“月”转换为factor指定为1:12 levels,获得由“年”,“月”进行分组“廉政”的sumspread以“宽”格式drop=FALSE

library(tidyverse) 
df %>% 
    group_by(year, month = factor(month, levels = 1:12)) %>% 
    summarise(int = sum(int)) %>% 
    spread(month, int, drop = FALSE, fill = 0) 
#  year `1` `2` `3` `4` `5` `6` `7` `8` `9` `10` `11` `12` 
#* <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 
#1 2014  3  2  2  1  2  0  0  4  1  5  5  6 
#2 2015  2  7  5  2  4  0  0  5  3  3  4  5 
#3 2016  0  4  5  5  2  0  0  3  2  1  5  2 

或者在一个单一的线路

library(data.table) 
dcast(setDT(df), year ~ factor(month, levels = 1:12), sum, drop = FALSE) 
# year 1 2 3 4 5 6 7 8 9 10 11 12 
#1: 2014 3 2 2 1 2 0 0 4 1 5 5 6 
#2: 2015 2 7 5 2 4 0 0 5 3 3 4 5 
#3: 2016 0 4 5 5 2 0 0 3 2 1 5 2 
使用

或者与xtabsbase R

xtabs(int~year+factor(month, levels = 1:12), df) 
+1

尼斯的答案!我更喜欢**'xtabs' **,因为它不需要任何附加软件包! – wittich

+1

对于**'xtabs' **,它有助于在输出中使用**'as.data.frame.matrix()**。 – wittich