Reputation: 656
I have 7 columns in my dataset. I want to convert 4 variables (2 to 5 column) from factor to date format. I can do it one column at a time, but I want to know if there is a shortcut through which I can convert all of them together.
Currently this is how I do it.
SampleData$column2<-as.Date(SampleData$column2,format="%Y/%m%/%d")
SampleData$column3<-as.Date(SampleData$column3,format="%Y/%m%/%d")
SampleData$column4<-as.Date(SampleData$column4,format="%Y/%m%/%d")
SampleData$column5<-as.Date(SampleData$column5,format="%Y/%m%/%d")
Upvotes: 3
Views: 9600
Reputation: 67778
Given the format of your dates, you may try this:
# sample data
df <- data.frame(a = 1:2,
d1 = factor(c("2013/01/01", "2014/01/01")),
d2 = factor(c("2013/01/01", "2014/01/01")),
b = 3:4)
df[ , 2:3] <- lapply(df[ , 2:3], as.Date)
str(df)
# 'data.frame': 2 obs. of 4 variables:
# $ a : int 1 2
# $ d1: Date, format: "2013-01-01" "2014-01-01"
# $ d2: Date, format: "2013-01-01" "2014-01-01"
# $ b : int 3 4
Upvotes: 10