【问题标题】:Insert rows where there are missing values在缺少值的地方插入行
【发布时间】:2018-02-19 10:28:18
【问题描述】:

数据是这样的:

 quarter name  week  value
 17Q3    abc   1     0.7
 17Q3    abc   3     0.65
 17Q3    def   1     0.13
 17Q3    def   2     0.04

我可以在缺少一周值的地方插入 value=0 的行,即输出应该是这样的:

quarter name  week  value
 17Q3    abc   1     0.7
 17Q3    abc   3     0.65
 17Q3    abc   2     0.0
 17Q3    def   1     0.13
 17Q3    def   2     0.04
 17Q3    def   3     0.0

需要填写到第 13 周。(即检查到 13)

【问题讨论】:

  • 试试library(dplyr);df1 %>% complete(quarter, name, week = full_seq(week, 1), fill = list(value = 0)) %>% arrange(quarter, name, id) %>% mutate(id = row_number()) %>% select(names(df1))
  • 谢谢..我已经尝试了 library(dplyr);df1 %>% complete(quarter, name, week = full_seq(week, 1), fill = list(value = 0)) ..得到类似找不到函数完成的错误
  • complete 来自tidyr 抱歉
  • 非常感谢..解决了这个问题。
  • 实际上我没有 id 列。在上面提到的代码之后,我得到了重复的行。库(tidyr);df1 %>% 完成(季度,名称,周 = full_seq(周,1),填充 = 列表(值 = 0))。

标签: r dataframe


【解决方案1】:

complete 中使用expand 怎么样。

library(tidyverse)
complete(df, expand(df, quarter, name, week), fill = list(value=0))

#   quarter name   week  value
#   <fct>   <fct> <int>  <dbl>
# 1 17Q3    abc       1 0.700 
# 2 17Q3    abc       2 0     
# 3 17Q3    abc       3 0.650 
# 4 17Q3    def       1 0.130 
# 5 17Q3    def       2 0.0400
# 6 17Q3    def       3 0   

或者,也许更容易理解:

df %>% expand(quarter, name, week) %>% left_join(df) %>% replace_na(list(value=0))

【讨论】:

  • 这会给出重复的结果
  • 在末尾添加%&gt;% distinct()
【解决方案2】:

这是tidyverse 的一个选项。我们得到缺少的行组合与completearrange 基于'季度'、'名称'和'id'的行,然后mutate'id' 到'row_number())andselect ` 列的顺序与原始数据集中的顺序相同

library(tidyverse)
df1 %>%
  complete(quarter, name, week = full_seq(week, 1), fill = list(value = 0)) %>%
  arrange(quarter, name, id) %>%
  mutate(id = row_number()) %>% 
  select(names(df1))
# A tibble: 6 x 5
#     id quarter name   week  value
#  <int> <chr>   <chr> <dbl>  <dbl>
#1     1 17Q3    abc    1.00 0.700 
#2     2 17Q3    abc    3.00 0.650 
#3     3 17Q3    abc    2.00 0     
#4     4 17Q3    def    1.00 0.130 
#5     5 17Q3    def    2.00 0.0400
#6     6 17Q3    def    3.00 0     

【讨论】:

  • 谢谢 Akrun..如果我们没有 id 列,有没有办法。我得到重复的行。一种方法是删除重复项。
  • 另一个更新。我需要填写到第 13 周。添加 full_seq(week,1,13) 没有帮助。
  • @buntysahoo 请在帖子中更新您的输入数据和预期输出
  • 更新了帖子本身。我需要检查到第 13 周并填写到 13。
  • 已解决...使用了独特的功能,它给出了准确的解决方案。非常感谢 Akrun。
猜你喜欢
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 2021-06-08
  • 2019-02-25
相关资源
最近更新 更多