I have a dataframe with a column called "Date" that is in the date format:
df<- data.frame(date=c("1997-01-01", "1997-01-02", "1997-01-03", "1997-01-04",
"1997-01-05", "1997-01-06" ,"1997-01-07" ,"1997-01-08","1998-01-12",
"1998-01-13", "1998-01-14", "1998-01-15" ,"1998-01-16", "1998-01-17",
"1998-01-18", "1998-01-19"))
And I need to make a column that changes the unique year/month combo in the Date
column to a continuous month variable. I have 20 years of data and would have months from 1-240.
So the example for the df above would return:
output<- data.frame(date=c("1997-01-01", "1997-01-02", "1997-01-03",
"1997-01-04", "1997-01-05", "1997-01-06" ,"1997-01-07" ,"1997-01-08","1998-01-12",
"1998-01-13", "1998-01-14", "1998-01-15" ,"1998-01-16", "1998-01-17",
"1998-01-18", "1998-01-19"), continuous_month=c("1", "1", "1", "1",
"1", "1" ,"1" ,"1","13", "13", "13", "13" ,"13", "13", "13", "13"))
NOTE: 01/1997 would be the first month, and I have skipped months 02/1997(2nd month)-12/1997 (12th month) in the example dataframe, so 01/1998 would be the 13th month in the series.
Select “Date” from the list of variable types. Then, on the right, select the format in which the date/time for that variable should appear (by selecting the date/time format in which the values already appear). Click OK. Now SPSS will recognize the variable as date/time.
To convert such dates to Stata dates, use the mdy function. It takes three numeric arguments: the month, day and year to be converted.
You can use year
and month
of lubridate
to extract relevant information
library(lubridate)
df$date = ymd(df$date)
temp = 12*(year(df$date) - min(year(df$date))) + month(df$date)
df$output = temp - min(temp) + 1
df$output
# [1] 1 1 1 1 1 1 1 1 13 13 13 13 13 13 13 13
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With