我有一个数据框,其中一个库仑具有以下结构:“ 2019-09-11 13:29:55:647 INFO”。我如何将该列分为两列,其中:第一列是:“ 2019-09-11 13:29:55”,第二列是:“ 647 INFO”?我想使用tiduverse分隔函数,但不能为分隔符写一个正则表达式。
我们在插入定界符后可以使用read.csv
cbind(df1, read.csv(text = sub(":(\\d+)$", ",\\1",
as.character(df1$datetime)), col.names =c('newcol1', 'newcol2'),
header = FALSE, stringsAsFactors = FALSE))
[如果我们使用的是tidyverse
,请以正则表达式为例指定sep
,即匹配:
,后跟仅数字(\\d+
),直到字符串的末尾($
)
library(tidyr)
separate(df1, datetime, into = c('newcol1', 'newcol2'), sep=":(?=\\d+$)")
# newcol1 newcol2
#1 2019-09-11 13:29:55 647
或使用extract
,将字符作为一个组捕获,直到最后一个:
,然后是数字,直到您的字符串的末尾
extract(df1, datetime, into = c('newcol1', 'newcol2'), "(.*):(\\d+)$")
df1 <- data.frame(datetime = "2019-09-11 13:29:55:647", stringsAsFactors = FALSE)