gpt4 book ai didi

r - 如何从单个向量排列 2x2 data.frame

转载 作者:行者123 更新时间:2023-12-04 11:59:29 24 4
gpt4 key购买 nike

我有以下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")

最佳答案

使用 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

关于r - 如何从单个向量排列 2x2 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54399732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com