向没有值的项x组对添加默认值(df%>%价差%>%聚集似乎很奇怪)

kas*_*rma 5 r dplyr tidyr

简洁版本

怎么做

df1 %>% spread(groupid, value, fill = 0) %>% gather(groupid, value, one, two)
Run Code Online (Sandbox Code Playgroud)

以更自然的方式?

长版

给定数据框

df1 <- data.frame(groupid = c("one","one","one","two","two","two", "one"),
                  value = c(3,2,1,2,3,1,22),
                  itemid = c(1:6, 6))
Run Code Online (Sandbox Code Playgroud)

对于许多itemid和groupid对,我们都有一个值,对于某些itemid,有些groupids没有值。我想为这些情况添加默认值。例如对于itemid 1和groupid“ two”没有值,我想在其中获取默认值的行中添加一个值。

以下tidyr代码可实现此目的,但感觉起来很奇怪(在此添加的默认值为0)。

df1 %>% spread(groupid, value, fill = 0) %>% gather(groupid, value, one, two)
Run Code Online (Sandbox Code Playgroud)

我正在寻找有关如何以更自然的方式执行此操作的建议。

由于在过去的几周里看了上面的代码,我可能对其效果感到困惑,所以我编写了一个包装它的函数:

#' Add default values for missing groups
#' 
#' Given data about items where each item is identified by an id, and every
#' item can have a value in every group; add a default value for all groups
#' where an item doesn't have a value yet.
add_default_value <- function(data, id, group, value, default) {
  id = as.character(substitute(id))
  group = as.character(substitute(group))
  value = as.character(substitute(value))
  groups <- unique(as.character(data[[group]]))

  # spread checks that the columns outside of group and value uniquely
  # determine the row.  Here we check that that already is the case within
  # each group using only id.  I.e. there is no repeated (id, group).
  id_group_cts <- data %>% group_by_(id, group) %>% do(data.frame(.ct = nrow(.)))
  if (any(id_group_cts$.ct > 1)) {
    badline <- id_group_cts %>% filter(.ct > 1) %>% top_n(1, .ct)
    stop("There is at least one (", id, ", ", group, ")",
         " combination with two members: (",
         as.character(badline[[id]]), ", ", as.character(badline[[group]]), ")")
  }

  gather_(spread_(data, group, value, fill = default), group, value, groups)
}
Run Code Online (Sandbox Code Playgroud)

最后说明:希望这样做的原因是,我的组是有序的(第1周,第2周,...),我希望每个ID在每个组中都有一个值,以便在对每个ID的组进行排序后,我可以使用cumsum每周总运行次数,也显示在总运行次数未增加的几周内。

sha*_*dow 3

complete开发版本中有一个新功能tidyr可以做到这一点。

df1 %>% complete(itemid, groupid, fill = list(value = 0))
##    itemid groupid value
## 1       1     one     3
## 2       1     two     0
## 3       2     one     2
## 4       2     two     0
## 5       3     one     1
## 6       3     two     0
## 7       4     one     0
## 8       4     two     2
## 9       5     one     0
## 10      5     two     3
## 11      6     one    22
## 12      6     two     1
Run Code Online (Sandbox Code Playgroud)