r - 如何根据特定值在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
功能,但在这种情况下不知道如何使用它。
有任何想法吗?
解决方案
我认为这是基于序列的逻辑的绝佳机会:
idx <- which(df$placement_status_type == "closing_bal")
df <- df[sort(c(sequence(nrow(df)),idx)),]
df[seq_along(idx) + idx,] <- NA
df
识别行,复制它们,并用NA
推荐阅读
- excel - 使用 Excel 的 2 个字符串查找和搜索
- python - 如何使用 Python 日志库写入 CSV?
- python - Altair - 通过滑块绑定过滤范围
- python - 在python中创建列表,if语句语法错误
- python - 无法弄清楚 keras 输入形状错误?
- angular - 根据用户请求构建 Angular 动态表单的最佳策略是什么?
- javascript - VueJS Typescript WebPack,无法通过拼接或删除从数组中删除对象
- sql - 递归地将字段连接到其解析的段
- python - QPaint 绘制带偏移的线条
- angular - 当我尝试从 github repo 在 stackblitz 上运行 Angular 7 代码时出现以下错误