在r中将一列拆分为两列

时间:2016-07-19 14:58:06

标签: r stringr

我的df看起来像这样:

Time
Week End 07-01-10
Week End 07-02-10

我希望它为

Column        Time
Week End   07-01-10
Week End   07-02-10 

我用googled包stringr会很有用,但我无法正确使用它,因为有两个空格。

3 个答案:

答案 0 :(得分:2)

您可以使用extract包中的tidyr,您可以在其中指定正则表达式来拆分列:

library(tidyr)
extract(df, Time, into = c("Column", "Time"), "(.*)\\s(\\S+)")
#     Column     Time
# 1 Week End 07-01-10
# 2 Week End 07-02-10

使用(.*)\\s(\\S+)捕获两个组并拆分空格,后面跟一个不包含空格\\S+的组。

如果您想使用stringr包,可以使用具有类似功能的str_match功能:

stringr::str_match(df$Time, "(.*)\\s(\\S+)")[, 2:3]
#      [,1]       [,2]      
# [1,] "Week End" "07-01-10"
# [2,] "Week End" "07-02-10"

strsplit如果您指定空格为数字之前的空格也有效,此处?=代表向前看,\\d是数字的缩写,相当于{{ 1}}:

[0-9]

答案 1 :(得分:1)

我们可以使用read.table中的base R。不需要包裹

read.table(text=sub("\\s+(\\S+)$", ",\\1", df1$Time), header=FALSE, 
     col.names = c("Column", "Time"), stringsAsFactors=FALSE, sep=",")
#    Column     Time
#1 Week End 07-01-10
#2 Week End 07-02-10

答案 2 :(得分:0)

这是一个基础R解决方案。

df <- data.frame(c("Week End 07-01-10", "Week End 07-02-10"),
                 stringsAsFactors=FALSE)
names(df) <- "Time"

# Assuming all columns end with (time?) in the same format.
df$Column <- substring(df$Time, 0, nchar(df$Time)-9)
df$Time <- substring(df$Time, nchar(df$Time)-8, nchar(df$Time))
df <- df[, c(2,1)]; df # Changing column order
相关问题