首页 > 解决方案 > 如何根据特定值在df中插入空白行

问题描述

我有一个汇总表,其中包括df下面的列。我想在列"closing_bal"中的值之后立即插入一个空白行placement_status_type

# This is part of the df that I have
df <- data.frame(stringsAsFactors=FALSE,
           referral_phase_code = c("-", "EA", "EA", "EA", "EA", "EA", "EA", "-", "-",
                                   "PPS", "PPS", "-", "OS", "-", "-", "EA",
                                   "EA", "EA", "EA", "EA", "EA", "-", "-", "PPS",
                                   "PPS", "-"),
         placement_status_type = c("opening_bal", "New", "Transfer", "Reinstated",
                                   "Suspended", "Trf to PPS", "Exit",
                                   "closing_bal", "opening_bal", "New", "Trf to EA",
                                   "closing_bal", "New", "closing_bal", "opening_bal",
                                   "New", "Transfer", "Reinstated", "Suspended",
                                   "Trf to PPS", "Exit", "closing_bal",
                                   "opening_bal", "New", "Trf to EA", "closing_bal")
      )

# This is the desired output
output_df <- data.frame(stringsAsFactors=FALSE,
                  referral_phase_code = c("-", "EA", "EA", "EA", "EA", "EA", "EA", "-", NA,
                                          "-", "PPS", "PPS", "-", NA, "OS",
                                          "-", NA, "-", "EA", "EA", "EA", "EA",
                                          "EA", "EA", "-", NA, "-", "PPS", "PPS",
                                          "-"),
                placement_status_type = c("opening_bal", "New", "Transfer", "Reinstated",
                                          "Suspended", "Trf to PPS", "Exit",
                                          "closing_bal", NA, "opening_bal", "New",
                                          "Trf to EA", "closing_bal", NA, "New",
                                          "closing_bal", NA, "opening_bal",
                                          "New", "Transfer", "Reinstated",
                                          "Suspended", "Trf to PPS", "Exit", "closing_bal",
                                          NA, "opening_bal", "New", "Trf to EA",
                                          "closing_bal")
             )

我知道add_row功能,但在这种情况下不知道如何使用它。

有任何想法吗?

标签: rtidyverse

解决方案


我认为这是基于序列的逻辑的绝佳机会:

idx <- which(df$placement_status_type == "closing_bal")

df <- df[sort(c(sequence(nrow(df)),idx)),]
df[seq_along(idx) + idx,] <- NA
df

识别行,复制它们,并用NA


推荐阅读