0

I have 50 variables named Date1 - Date50 stored in data1 (among other variables).

The initial format of Date1 - Date50 is "factor". The values are like "24.01.2014".

How can I format all 50 variables as a Date at once?

For a single variable the following command works fine:

data1$Date1<-as.Date("data1$Date1", format="%d.%m.%Y")

I tried several ways with "lapply" but without success.

Thanks!

Georg
  • 61
  • 1
  • 8
  • Try `data1[] <- lapply(data1, function(x) as.Date(x, '%d.%m.%Y'))` asssuming that you have a 50 column dataset and all the columns you want to change to 'Date' class. – akrun Jul 30 '15 at 10:50
  • I get a error message.Remember "data1" has also several other variables. If I has only the date1-date50 columns it would probably work. – Georg Jul 30 '15 at 10:53
  • In that case, you need to subset the 'Date' columns alone. I didn't read that you have different other columns. – akrun Jul 30 '15 at 10:54

1 Answers1

1

I believe this should do it for you.

data1[, paste0("Date", 1:50)] <- 
  lapply(data1[, paste0("Date", 1:50)],
         function(x) as.Date(as.character(x), format = "%d.%m.%Y"))
Benjamin
  • 16,897
  • 6
  • 45
  • 65