0

I have 66 data frames that I need to transform the "Date" column "as.Date". I dont know how to do it at once. I'm going like this:

dat2003q1$Date<-as.Date(as.character(dat2003q1),format="%m/%d/%Y")
dat2003q2$Date<-as.Date(as.character(dat2003q2),format="%m/%d/%Y")
dat2003q3$Date<-as.Date(as.character(dat2003q3),format="%m/%d/%Y")

And so on...

There is a way to do it for all data frames at once? Ive found a solution for multiple columns in the same data frame, but not like this.

Tks

Jorge Dias
  • 49
  • 7
  • 2
    do you have 66 data frames in your workspace? you should be keeping them in a list and work with the apply functions – rawr Nov 26 '14 at 01:19
  • Yes, I have 66 data frames in my workspace. By your comments, it seems to be an unusual thing to do but I have not much experience in R. Tks – Jorge Dias Nov 27 '14 at 00:21

1 Answers1

1

Try

lst <- lapply(mget(ls(pattern='^dat2003q\\d+')), function(x) {
                     x$Date <- as.Date(as.character(x$Date), format='%m/%d/%Y')
                       x})

If you want to update the datasets in the global environment with this change (which is not that recommended as you can do all the necessary operations within the list and later you may save the datasets using read.table)

list2env(lst, envir=.GlobalEnv)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thats exactly what Iam looking for. Tks. Iam new in R so I dont get it why should I work with list instead datasets. And sorry for my bad english. – Jorge Dias Nov 27 '14 at 00:11
  • @Jorge Dias The reason is that you have to create 66 objects. I am guessing you read all those datasets individually. Then, if you want to do some calculations in all the datasets at once (just like the situation you described), you have to use either a `for` loop or use `lapply` by putting them in a list. So, instead of creating all those objects, you could have read them `lst <- lapply(list.files(), function(x) read.table(x, header=TRUE, sep=''))` if the files are all in the working directory. – akrun Nov 27 '14 at 04:11
  • Thank you again. Your guessing is right. Now I understand why I should work with lists. I realized when I used the function lst <- lapply(list.files(), function(x) read.csv(x, header=TRUE) the list does not assumed names for the data.frames. There is a command to fix that? After that Im using lst <- lapply(lst, function(x) { x$Date <- as.Date(as.character(x$Date), format='%m/%d/%Y') x}) and lst2 <- lapply(lst, function(x) { x<-as.xts(x[,-1],order.by = x$Date) }) I suppose I can use the same logic, right? Tks. – Jorge Dias Nov 28 '14 at 12:45
  • @JorgeDias When you create `lst` using the code that you showed, you are not naming the `lst` elements. you can name the `lst` elements as `names(lst) <- gsub("\\.txt", '', list.files())` assuming the file extension is `.txt` (not tested) or you can use `setNames(lapply(...` – akrun Nov 28 '14 at 12:49