我需要将日期(m/d/y格式)转换为3个单独的列,我希望在其中运行算法.(我正在尝试将日期转换为Julian Day Numbers).为另一个用户看到了这个建议,使用Oracle将数据分成多个列.我正在使用R而且我一直坚持如何恰当地编码.A1,A2 ......代表我的新列标题,与"更新集"部分的格式差异是什么?
update <tablename> set A1 = substr(ORIG, 1, 4),
A2 = substr(ORIG, 5, 6),
A3 = substr(ORIG, 11, 6),
A4 = substr(ORIG, 17, 5);
Run Code Online (Sandbox Code Playgroud)
我正在努力提高我在R中的技能,但无法想象这一点...任何帮助都非常感激.提前致谢... :)
Rei*_*son 21
我使用对象的format()方法Date来拉开R中的日期.使用Dirk datetext,我将如何将日期分解为其组成部分:
datetxt <- c("2010-01-02", "2010-02-03", "2010-09-10")
datetxt <- as.Date(datetxt)
df <- data.frame(date = datetxt,
year = as.numeric(format(datetxt, format = "%Y")),
month = as.numeric(format(datetxt, format = "%m")),
day = as.numeric(format(datetxt, format = "%d")))
Run Code Online (Sandbox Code Playgroud)
这使:
> df
date year month day
1 2010-01-02 2010 1 2
2 2010-02-03 2010 2 3
3 2010-09-10 2010 9 10
Run Code Online (Sandbox Code Playgroud)
注意其他几个人所说的; 您可以在不拆分各种日期组件的情况下获取Julian日期.我添加了这个答案,以展示如果你需要别的东西你可以分手.
给定一个文本变量x,如下所示:
> x
[1] "10/3/2001"
Run Code Online (Sandbox Code Playgroud)
然后:
> as.Date(x,"%m/%d/%Y")
[1] "2001-10-03"
Run Code Online (Sandbox Code Playgroud)
将其转换为日期对象.然后,如果你需要它:
> julian(as.Date(x,"%m/%d/%Y"))
[1] 11598
attr(,"origin")
[1] "1970-01-01"
Run Code Online (Sandbox Code Playgroud)
给你一个朱利安日期(相对于1970-01-01).
不要尝试子串的东西......
有关更多信息,请参阅帮助(as.Date).
快速的:
Julian日期转换器已经存在于基础R中,参见例如help(julian).
一种方法可能是将日期解析为POSIXlt,然后读取组件.其他日期/时间类和包也可以工作但是对于基础R有一些东西可以说.
将日期解析为字符串几乎总是一种糟糕的方法.
这是一个例子:
datetxt <- c("2010-01-02", "2010-02-03", "2010-09-10")
dates <- as.Date(datetxt) ## you could examine these as well
plt <- as.POSIXlt(dates) ## now as POSIXlt types
plt[["year"]] + 1900 ## years are with offset 1900
#[1] 2010 2010 2010
plt[["mon"]] + 1 ## and months are on the 0 .. 11 intervasl
#[1] 1 2 9
plt[["mday"]]
#[1] 2 3 10
df <- data.frame(year=plt[["year"]] + 1900,
month=plt[["mon"]] + 1, day=plt[["mday"]])
df
# year month day
#1 2010 1 2
#2 2010 2 3
#3 2010 9 10
Run Code Online (Sandbox Code Playgroud)
而且当然
julian(dates)
#[1] 14611 14643 14862
#attr(,"origin")
#[1] "1970-01-01"
Run Code Online (Sandbox Code Playgroud)
小智 6
要将日期(m/d/y 格式)转换为 3 个单独的列,请考虑 df,
df <- data.frame(date = c("01-02-18", "02-20-18", "03-23-18"))
df
date
1 01-02-18
2 02-20-18
3 03-23-18
Run Code Online (Sandbox Code Playgroud)
转换为日期格式
df$date <- as.Date(df$date, format="%m-%d-%y")
df
date
1 2018-01-02
2 2018-02-20
3 2018-03-23
Run Code Online (Sandbox Code Playgroud)
要获得包含年、月和日期的三个单独的列,
library(lubridate)
df$year <- year(ymd(df$date))
df$month <- month(ymd(df$date))
df$day <- day(ymd(df$date))
df
date year month day
1 2018-01-02 2018 1 2
2 2018-02-20 2018 2 20
3 2018-03-23 2018 3 23
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。