我有以下data.frame:
v1<-c("8/12/2018", "hello, how are you", "9/9/2016", "What is going on?","the number three", "9/18/2015", "hello", "9/8/1999","not going", "where to next?")
(df<-as.data.frame(v1, stringsAsFactors=FALSE))
v1
1 8/12/2018
2 hello, how are you
3 9/9/2016
4 What is going on?
5 the number three
6 9/18/2015
7 hello
8 9/8/1999
9 not going
10 where to next?
我想生成一个函数,该函数将读取每一行,并将紧跟日期的行之后的每一行移动到新列,并删除不紧随日期的所有行。根据上面的示例,我想要的输出如下:
v1 value
1 8/12/2018 hello, how are you
2 9/9/2016 What is going on?
3 9/18/2015 hello
4 9/8/1999 not going
我的直觉是先复制v1
,然后再复制lead
,然后使用ifelse
创建一个新列,如下所示,但是我没有运气,也不知道从何而来甚至在那里。
df$value<-ifelse(v1="^\d{1,2}\/\d{1,2}\/\d{4}$", lead(v1),"NA")
答案 0 :(得分:4)
使用grep
的基本R选项。首先找出严格遵循日期格式的索引,然后使用该索引的下一行创建带有新列的新数据框。
inds <- grep("^\\d{1,2}/\\d{1,2}/\\d{4}$", df$v1)
with(df, data.frame(v1 = v1[inds], value = v1[inds + 1]))
# v1 value
#1 8/12/2018 hello, how are you
#2 9/9/2016 What is going on?
#3 9/18/2015 hello
#4 9/8/1999 not going
答案 1 :(得分:3)
一个选择是从“ v1”创建新列,作为列的lead
,filter
仅创建以数字或“ v1”格式为Date
的元素
library(tidyverse)
df %>%
mutate(value = lead(v1)) %>%
filter(grepl("^\\d+", v1))
#or
#filter(!is.na(mdy(v1)))
# v1 value
#1 8/12/2018 hello, how are you
#2 9/9/2016 What is going on?
#3 9/18/2015 hello
#4 9/8/1999 not going