Converting factor to Date format, getting stream of NAs?

r
lubridate
date
data_science
datamanipulation

#1
x <- c("4-Jan-11", "17-Feb-11", "11-May-10", "5-Feb-11", "13-Apr-10", "21-Jan-11", "3-Jun-10", "22-Oct-10", "17-Nov-10", "6-Mar-11", "6-Nov-10", "12-May-10", "5-Apr-10", "11-Jan-11", "4-May-10", "10-Aug-10", "31-Jul-10", "5-Dec-10", "9-Apr-10", "22-May-10", "17-Feb-11", "13-May-10", "2-Jan-11", "17-May-10", "22-Apr-10")

df <- data.frame(as.factor(x))

Resulting output should be in YMD and Date format

You can use Lubridate or Base R functions.


#2

Hi Ashish,

df <- data.frame(as.Date(x,“format=”%d-%m-%Y")

Thanks,
Abhishek Das


#3

@abhishek.gitam

x <- c(“4-Jan-11”, “17-Feb-11”, “11-May-10”, “5-Feb-11”, “13-Apr-10”, “21-Jan-11”, “3-Jun-10”, “22-Oct-10”, “17-Nov-10”, “6-Mar-11”, “6-Nov-10”, “12-May-10”, “5-Apr-10”, “11-Jan-11”, “4-May-10”, “10-Aug-10”, “31-Jul-10”, “5-Dec-10”, “9-Apr-10”, “22-May-10”, “17-Feb-11”, “13-May-10”, “2-Jan-11”, “17-May-10”, “22-Apr-10”)

df <- data.frame(as.factor(x))

#changing name of first column as dates
names(df)[1] <- “dates”
#checking class of dates
class(x$dates)

[1] “factor”
#converting as dataframe
x$dates <- as.Date(x$dates, format = “%d/%m/%y”)
#checking class again
[1] “Date”

x

I’m getting continuous stream of NA output, why?


#4

Hi @ashish25sahu

use data.frame(x, stringsAsFactors =FALSE) and now you can use as.Date()

Alain


#5

Hi @ashish25sahu

The issue was with the “Date Format” in your code! Using correct format; the code is working as expected.

Code for reference:

x <- c(“4-Jan-11”, “17-Feb-11”, “11-May-10”, “5-Feb-11”, “13-Apr-10”, “21-Jan-11”, “3-Jun-10”, “22-Oct-10”, “17-Nov-10”, “6-Mar-11”, “6-Nov-10”, “12-May-10”, “5-Apr-10”, “11-Jan-11”, “4-May-10”, “10-Aug-10”, “31-Jul-10”, “5-Dec-10”, “9-Apr-10”, “22-May-10”, “17-Feb-11”, “13-May-10”, “2-Jan-11”, “17-May-10”, “22-Apr-10”)

df <- data.frame(x)
names(df)[1] <- “dates"
class(df$dates)
df$dates <- as.Date(df$dates, format=”%d-%b-%y")

For reference; date-formats-in-r