r - 如何根据列中的字符串在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)
)
解决方案
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), ])))
推荐阅读
- java - 如何在 Java 中实现 Graphic2D 对象的颜色变化?
- c - 在汇编 x86 中交换 2 个整数
- treeview - 网络树不集中
- google-cloud-storage - 如何正确授权对 Google Cloud Storage API 的请求?
- c - 如何检测管道输入的缺失
- wpf - WPF PixelShader,其输入是 UIElement 下面的数据而不是 UIElement
- machine-learning - model.cv_results_ 中的rank_test_score 代表什么?
- ruby - macOS Mojave 'ruby/config.h' 文件未找到
- php - mysqli_query() 期望参数 1 为 mysqli,给定布尔值
- python - 过滤列表中的多个数据框列