R 如何从单个列中将年、月、日和时间提取到4个不同的列中
我有一个数据集,由一列组成,如R 如何从单个列中将年、月、日和时间提取到4个不同的列中,r,R,我有一个数据集,由一列组成,如 Year 1/1/1996 9:00 1/2/1996 9:00 1/3/1996 9:00 1/4/1996 9:00 1/5/1996 9:00 1/6/1996 9:00 1/7/1996 9:00 1/8/1996 9:00 1/9/1996 9:00 1/10/1996 9:00 我想创建4个不同的列,看起来像这样 Year Month Day Year Time 1/1/1996 9:00 1 1
Year
1/1/1996 9:00
1/2/1996 9:00
1/3/1996 9:00
1/4/1996 9:00
1/5/1996 9:00
1/6/1996 9:00
1/7/1996 9:00
1/8/1996 9:00
1/9/1996 9:00
1/10/1996 9:00
我想创建4个不同的列,看起来像这样
Year Month Day Year Time
1/1/1996 9:00 1 1 1996 9:00
1/2/1996 9:00 1 2 1996 9:00
1/3/1996 9:00 1 3 1996 9:00
1/4/1996 9:00 1 4 1996 9:00
1/5/1996 9:00 1 5 1996 9:00
1/6/1996 9:00 1 6 1996 9:00
1/7/1996 9:00 1 7 1996 9:00
1/8/1996 9:00 1 8 1996 9:00
1/9/1996 9:00 1 9 1996 9:00
1/10/1996 9:00 1 10 1996 9:00
在R中可以这样做吗 我们可以使用
从库(tidyr)
中分离。我们将在中创建的新变量指定为。其他参数包括指定分隔符的sep
,remove
返回是否保留原始列,以及使用type.convert=TRUE更改新变量的列类
library(tidyr)
separate(df1, Year, into=c('Month', 'Day', 'Year', 'Time'),
sep='[/ ]', remove=FALSE, type.convert=TRUE)
# Year Month Day Year Time
#1 1/1/1996 9:00 1 1 1996 9:00
#2 1/2/1996 9:00 1 2 1996 9:00
#3 1/3/1996 9:00 1 3 1996 9:00
#4 1/4/1996 9:00 1 4 1996 9:00
#5 1/5/1996 9:00 1 5 1996 9:00
#6 1/6/1996 9:00 1 6 1996 9:00
#7 1/7/1996 9:00 1 7 1996 9:00
#8 1/8/1996 9:00 1 8 1996 9:00
#9 1/9/1996 9:00 1 9 1996 9:00
#10 1/10/1996 9:00 1 10 1996 9:00
另一个选项是来自data.table
的tstrsplit
。我们将“data.frame”转换为“data.table”(setDT(df1)
),拆分“Year”列(tstrsplit(Year,…)
),并分配输出(:=
)以创建新列
library(data.table)#v1.9.6+
setDT(df1)[, c('Month', 'Day', 'year', 'Time') := tstrsplit(Year, '[/ ]',
type.convert=TRUE)]
或者另一个选项是来自库(splitstackshape)
的cSplit
library(splitstackshape)
cSplit(df1, 'Year', '[/ ]', fixed=FALSE, drop=FALSE, type.convert=TRUE)
数据
df1您可以使用一些包
库(readr)
图书馆(dplyr)
图书馆(lubridate)
图书馆(stringi)
df谢谢,我尝试了separate(df1,Year,into=c('Month','Day','Year','Time'),sep='[/]',remove=FALSE,type.convert=TRUE)
。但是它在if(!after)c(values,x)else if(after>=lengx)c(x,values)else c(x[1L:after]中给出了一个错误,:参数长度为零。
@ShretaGhimire你在我的帖子中使用相同的数据吗?我使用的是tidyr_0.3.1.9000
@ShretaGhimire我还更新了几个其他选项。检查这是否对你有效。谢谢。它非常适合我的数据集。现在我可以在我拥有的几个大数据框中拆分年份。@ShretaGhimire Than谢谢你的反馈。很高兴知道它有效。
df1 <- structure(list(Year = c("1/1/1996 9:00", "1/2/1996 9:00",
"1/3/1996 9:00",
"1/4/1996 9:00", "1/5/1996 9:00", "1/6/1996 9:00", "1/7/1996 9:00",
"1/8/1996 9:00", "1/9/1996 9:00", "1/10/1996 9:00")), .Names = "Year",
class = "data.frame", row.names = c(NA, -10L))