首页 > 解决方案 > 将条件前后的行插入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)                 

标签: rdataframedata.table

解决方案


您需要执行三个步骤:

  • 查找日期位置(使用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,+


推荐阅读