2

The time coloumn of my dataframe looks like the following

# time
# %Y-%m-%d
# 2000-01-01
# 2000-01-02
# ...

I would like to split the date coloumn in one for the year and one for the month (I dont need the days) So the output should look like the following:

# year  month
# %Y    %m
# 2000  01
# 2000  02
# ...
bwi321
  • 123
  • 6

3 Answers3

1

In the lubridate package, use the year() and month() functions to extract them, respectively, from a date object.

library(data.table)
library(lubridate)

DT <- as.data.table(yourDataFrame)

DT[, Date := ymd(time)]
DT[, year := year(Date)]
DT[, month := month(Date)]
altabq
  • 1,322
  • 1
  • 20
  • 33
1

Yo can try separate, e.g.,

library(dplyr)
library(tidyr)

df %>% separate(d,c("year","month"),extra = "drop")

which gives

> df %>% separate(d,c("year","month"),extra = "drop")
  year month
1 2020    01
2 2020    02

Data

df <- data.frame(d = c("2020-01-01","2020-02-01"))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

Base 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


user12256545
  • 2,755
  • 4
  • 14
  • 28