r语言 - 如何使用合并,以便我拥有所有时间的数据



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

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 的月份;我该怎么做?我现在正在尝试使用合并功能,但欣赏任何其他方法。

我们可以使用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'

在基本 R 中使用 merge(其中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))

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

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

相关内容

最新更新