r - 将条件前后的行插入data.frame
问题描述
我有这样的数据:
df <- data.frame(V1=c("stuff", "2nd June 2018", "otherstuff1", "baseball","", "142", "otherstuff2", "football","", "150", "4th June 2018", "otherstuff99", "hockey","", "160", "otherstuff100", "baseball", "", "190", "otherstuff5", "lacrosse", "200", "9th June 2018"), stringsAsFactors = F)
我想按条件插入一行,在任何日期值的书挡上插入新单元格“日期”。日期之间有随机数量的其他单元格:
df.desired <- data.frame(V1=c("stuff","date", "2nd June 2018","date" ,"otherstuff1", "baseball","", "142", "otherstuff2", "football","", "150","date", "4th June 2018","date", "otherstuff99", "hockey","", "160", "otherstuff100", "baseball", "", "190", "otherstuff5", "lacrosse", "200", "date", "9th June 2018","date"), stringsAsFactors=F)
解决方案
您需要执行三个步骤:
- 查找日期位置(使用
grep
) date
创建具有行空间的新 data.frame- 添加
date
到新的data.frame
代码:
# Find position of `month year`
foo <- grep(paste(month.name, "\\d+$", collapse = "|"), df$V1)
# Expand original data.frame with space for data
dfDesired <- data.frame(x = df$V1[sort(c(1:nrow(df), foo, foo))], stringsAsFactors = FALSE)
# Find position for date in expanded data.frame
bar <- foo + seq(by = 2, length.out = length(foo))
# Add date
dfDesired$x[c(bar - 1, bar + 1)] <- "date"
笔记:
grep
用字符串完成:paste(month.name, "\\d+$", collapse = "|")
"一月 \d+$|二月 \d+$|三月 \d+$|四月 \d+$|五月 \d+$|六月 \d+$|七月 \d+$|八月 \d+$|九月 \d+$|十月 \d+$ |11 月 \d+$|12 月 \d+$"
我们需要bar
位置作为新 data.frame 中的行移动:1,3,5,+
推荐阅读
- arrays - 尝试在 ruby 中复制然后旋转数组 - 为 nil:NilClass (NoMethodError) 获取错误未定义方法“[]”
- bash - BASH 脚本:如何替换文件路径字符串中的字符串?
- python - 我无法在 PyGame 中正确跟踪 KEYDOWN 事件
- database - 一个人如何获得在线学习 Redis 的帮助
- c++ - c ++计算数组中的单词
- c# - 使用 linq 从 2 个数据表中选择和分组数据,并在 datagridview 上显示结果
- python - 无法强制scrapy使用重定向的url进行回调
- qmake - 如何防止 make clean 删除 qmake 项目中的某个文件
- wordpress - 如何从字段键中获取值(Ninja Forms)
- request - 传递以字符 [ 开头的 JSON 请求会出现错误:使用 GET 操作的请求格式无效