【问题标题】:Insert rows in dataframe based on condition - the Tidyverse way [duplicate]根据条件在数据框中插入行 - Tidyverse 方式 [重复]
【发布时间】:2021-01-09 04:39:23
【问题描述】:

这是一个数据框

# 5 companies observed each day for 10 days
df <- tibble(
  company = rep(LETTERS[1:5], 10),
  value = rep(sample(100, 5), 10),
  date = rep(seq(as.Date("2020-01-01"), as.Date("2020-01-10"), 1), each = 5)
)
df

现在数据发生了一些变化,公司的一些 E 行被删除了。

df_error <- df[-c(5, 10, 15, 20), ]
df_error

添加回 E 行的最简单的 Tidyverse 方法是什么。 价值无所谓。 E行的日期与上面的D行相同。

我从以下内容开始,但不知道如何继续:

# Find all D occurrences
e_idx <- which(df_error$company == "D")
e_idx

# If there is not an E in the next row, get the index. These need E rows below each index value. 
rows_need_e_below <- ifelse(df_error[e_idx + 1, 1] != "E", e_idx, NA)
rows_need_e_below

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    如果您知道您的数据应该包含“A”到“E”公司,您可以使用complete

    tidyr::complete(df_error, date, company = LETTERS[1:5])
    

    或更笼统地说:

    unique_company <- c('A', 'B', 'C', 'D', 'E')
    tidyr::complete(df_error, date, company = unique_company)
    
    # A tibble: 50 x 3
    #   date       company value
    #   <date>     <chr>   <int>
    # 1 2020-01-01 A          87
    # 2 2020-01-01 B           5
    # 3 2020-01-01 C          40
    # 4 2020-01-01 D          67
    # 5 2020-01-01 E          NA
    # 6 2020-01-02 A          87
    # 7 2020-01-02 B           5
    # 8 2020-01-02 C          40
    # 9 2020-01-02 D          67
    #10 2020-01-02 E          NA
    # … with 40 more rows
    

    value 列默认为NA 值。如果你想用特定的值填充它,你可以使用completefill 参数。例如,要填充 0,您可以这样做:

    tidyr::complete(df_error, date, company = unique_company, fill = list(value = 0))
    

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多