首页 > 解决方案 > 如何根据列中的字符串在df中输入几个空行

问题描述

我有一个输出 df,我试图closing_bal在名为placement_status_type. 这个想法是,在我插入空白行后,我将其保存为 excel 文件,以便最终用户轻松读取 excel 中的数字。

我知道该add_row功能,但无法找到在条件下使用它的方法。

sample data:
df <- data.frame(stringsAsFactors=FALSE,
         placement_status_type = c("opening_bal", "New", "Transfer", "Reinstated",
                                   "Suspended", "Exit", "closing_bal",
                                   "opening_bal", "New", "Transfer", "Reinstated",
                                   "Suspended", "Exit", "closing_bal", "opening_bal",
                                   "New", "Transfer", "Exit", "closing_bal",
                                   "opening_bal", "New", "Exit", "closing_bal",
                                   "Transfer", "Exit", "closing_bal", "Transfer",
                                   "Suspended", "Exit", "closing_bal"),
                        Aug_18 = c(173, 11, -6, 16, -21, -9, 164, 5, 4, 0, 3, 0, -2,
                                   10, 17, 6, -1, -4, 18, -1, 0, 0, -1, 0, 0,
                                   0, 0, 0, 0, 0)
      )

标签: rtidyverse

解决方案


add_row一次只能添加一行。我们可以在每次出现“closure_bal”时拆分数据帧,然后add_row为每个组拆分。

library(tidyverse)

df %>%
   group_split(c(0, 
     cumsum(placement_status_type == "closing_bal")[-nrow(df)]), keep = FALSE) %>%
   map_dfr(~add_row(., placement_status_type = "", Aug_18 = 0))


# A tibble: 36 x 2
#   placement_status_type Aug_18
#   <chr>                  <dbl>
# 1 opening_bal              173
# 2 New                       11
# 3 Transfer                  -6
# 4 Reinstated                16
# 5 Suspended                -21
# 6 Exit                      -9
# 7 closing_bal              164
# 8 ""                         0
# 9 opening_bal                5
#10 New                        4
# … with 26 more rows

do同样,如果我们想避免拆分和行绑定数据框,我们也可以使用

df %>%
 group_by(group = c(0, 
         cumsum(placement_status_type == "closing_bal")[-nrow(df)])) %>%
 do(add_row(., placement_status_type = "", Aug_18 = 0)) %>%
 ungroup() %>%
 select(-group)

作为一般解决方案,如果我们想要多次添加特定行,我们可以将其创建为单独的tibble

add_df <- tibble(placement_status_type = "", Aug_18 = 0)

并相应地重复

n <- 3

df %>%
  group_split(c(0, 
   cumsum(placement_status_type == "closing_bal")[-nrow(df)]), keep = FALSE) %>%
   map_dfr(~bind_rows(., add_df[rep(seq_len(nrow(add_df)), n), ]))

do这样就可以了

df %>%
  group_by(group = c(0, 
    cumsum(placement_status_type == "closing_bal")[-nrow(df)])) %>%
  do(bind_rows(., add_df[rep(seq_len(nrow(add_df)), n), ])) %>%
  ungroup() %>%
  select(-group)

所有这些都可以在基础 R 中实现

do.call(rbind, lapply(split(df, 
  c(0, cumsum(df$placement_status_type == "closing_bal")[-nrow(df)])), function(x) 
   rbind(x, add_df[rep(seq_len(nrow(add_df)), n), ])))

推荐阅读