插入缺少值的行

时间:2018-02-19 10:28:18

标签: r dataframe

数据如下:

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

我可以插入值= 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)

2 个答案:

答案 0 :(得分:1)

Dim src, dst as Workbook dst= ThisWorkbook 'Destination is your current workbook 'Define the src inside your IF-ELSE tree based on 'B7' cell value 'Use the statement below for each cell value with address in the 'Range' quotes dst.Range("").Value= src.Range("").Value 中使用expand怎么样。

complete

或者,也许更容易理解:

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   

答案 1 :(得分:0)

以下是tidyverse的一个选项。我们根据“季度”,“名称”和“ID”获取了completearrange行的缺失组合,然后将mutate'id'添加到'row_number( ))and选择列,使其具有与原始数据集中相同的顺序

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     
相关问题