在R中拆分日期
我的数据帧的时间列如下所示在R中拆分日期,r,dataframe,date,R,Dataframe,Date,我的数据帧的时间列如下所示 # time # %Y-%m-%d # 2000-01-01 # 2000-01-02 # ... 我想把日期栏分为一年一个月(我不需要天数) 因此,输出应如下所示: # year month # %Y %m # 2000 01 # 2000 02 # ... 在lubridate包中,使用year()和month()函数分别从日期对象中提取它们 library(data.table) library(lubridate) DT <- as.d
# time
# %Y-%m-%d
# 2000-01-01
# 2000-01-02
# ...
我想把日期栏分为一年一个月(我不需要天数)
因此,输出应如下所示:
# year month
# %Y %m
# 2000 01
# 2000 02
# ...
在
lubridate
包中,使用year()
和month()
函数分别从日期对象中提取它们
library(data.table)
library(lubridate)
DT <- as.data.table(yourDataFrame)
DT[, Date := ymd(time)]
DT[, year := year(Date)]
DT[, month := month(Date)]
库(data.table)
图书馆(lubridate)
DT在lubridate
包中,使用year()
和month()
函数分别从日期对象中提取它们
library(data.table)
library(lubridate)
DT <- as.data.table(yourDataFrame)
DT[, Date := ymd(time)]
DT[, year := year(Date)]
DT[, month := month(Date)]
库(data.table)
图书馆(lubridate)
DTYo可以尝试分离
,例如
library(dplyr)
library(tidyr)
df %>% separate(d,c("year","month"),extra = "drop")
给
> df %>% separate(d,c("year","month"),extra = "drop")
year month
1 2020 01
2 2020 02
数据
df <- data.frame(d = c("2020-01-01","2020-02-01"))
dfYo可以尝试separate
,例如
library(dplyr)
library(tidyr)
df %>% separate(d,c("year","month"),extra = "drop")
给
> df %>% separate(d,c("year","month"),extra = "drop")
year month
1 2020 01
2 2020 02
数据
df <- data.frame(d = c("2020-01-01","2020-02-01"))
dfBase R:
# data:
time<-seq.Date(from = as.Date("2000/1/1"),to=as.Date("2000/5/1"),by="days")
df<-data.frame(ID=1:length(time), time= time)
# months
df$month<-month(df$time)
# or:
df$month.name<-months(df$time)
df
#数据:
时间baser:
# data:
time<-seq.Date(from = as.Date("2000/1/1"),to=as.Date("2000/5/1"),by="days")
df<-data.frame(ID=1:length(time), time= time)
# months
df$month<-month(df$time)
# or:
df$month.name<-months(df$time)
df
#数据:
时间或使用extract
,iniseparate
,如果只指定两个,则可以选择extra='drop'
columns@akrun谢谢!现在我了解了更多关于separate
(我以前没有使用dplyr
)的内容:POr使用extract
,iniseparate
,如果只指定两个columns@akrun谢谢!现在我了解了更多关于separate
(我以前没有使用dplyr
)的知识:P