如何使用合并以便我始终拥有数据?

时间:2017-04-10 09:09:18

标签: r merge

我正在尝试更改所有实体在所有可能的时间(月)都具有价值的数据。这就是我正在尝试的;

Class  Value  month
  A      10     1
  A      12     3
  A      9      12
  B      11     1
  B      10     8

从上面的数据中,我想得到以下数据;

Class  Value  month
  A      10     1
  A      NA     2
  A      12     3
  A      NA     4
        ....
  A      9      12
  B      11     1
  B      NA     2
        ....
  B      10     8
  B      NA     9
        ....
  B      NA     12

所以我希望所有可能的细胞都在1到12个月内完成; 我怎样才能做到这一点?我现在正在尝试使用合并功能,但是欣赏任何其他方法。

3 个答案:

答案 0 :(得分:4)

我们可以使用tidyverse

library(tidyverse)
df1 %>%
   complete(Class, month = min(month):max(month)) %>% 
   select_(.dots = names(df1)) %>%  #if we need to be in the same column order
   as.data.frame() #if needed to convert to 'data.frame'

答案 1 :(得分:3)

在使用merge的基地R中(其中df是您的数据):

res <- data.frame(Class=rep(levels(df$Class), each=12), value=NA, month=1:12)
merge(df, res, by = c("Class", "month"), all.y = TRUE)[,c(1,3,2)]

   # Class Value month
# 1      A    10     1
# 2      A    NA     2
# 3      A    12     3
# 4      A    NA     4
# 5      A    NA     5
# 6      A    NA     6
# 7      A    NA     7
# 8      A    NA     8
# 9      A    NA     9
# 10     A    NA    10
# 11     A    NA    11
# 12     A     9    12
# 13     B    11     1
# 14     B    NA     2
# 15     B    NA     3
# 16     B    NA     4
# 17     B    NA     5
# 18     B    NA     6
# 19     B    NA     7
# 20     B    10     8
# 21     B    NA     9
# 22     B    NA    10
# 23     B    NA    11
# 24     B    NA    12
df <- structure(list(Class = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("A", 
"B"), class = "factor"), Value = c(10L, 12L, 9L, 11L, 10L), month = c(1L, 
3L, 12L, 1L, 8L)), .Names = c("Class", "Value", "month"), class = "data.frame", row.names = c(NA, 
-5L))

答案 2 :(得分:1)

要添加@ akrun的答案,如果要将NA值替换为0,则可以执行以下操作:

library(dplyr)
library(tidyr)

df1 %>%
complete(Class, month = min(month):max(month)) %>%
mutate(Value = ifelse(is.na(Value),0,Value))