2

I have multiple data frames in my R environment eg. data1,data2,data3. The first column is a date column having header "X"(same header in all data frames)but its class is showing as character. So i want to use as.Date() function on the first column of all the dataframes in my environment.

data1$X <- as.Date(data1$X) 

The above line works fine for one data frame. But I Want to use a for loop for all the data frames. I have a list of the names of all the data frames.

list <- c("data1", "data2", "data3")

I tried doing the following

for (i in list) {
  i$x <- as.Date(i$x)
}

which doesn't work.

Any help will be appreciated.

jogo
  • 12,469
  • 11
  • 37
  • 42
  • Your object `list` is a character vector. So at `i$x` you try something like `"data1"$x` (for example). BTW: "doesn't work" is not enough information, certainly you got an error message. Please put the error message in your question! – jogo Oct 26 '16 at 06:14
  • the error when i run for (i in list) { i$x <- as.Date(i$x) } is Error in i$x : $ operator is invalid for atomic vectors – Parikshit Sohoni Nov 03 '16 at 17:02

4 Answers4

1

Better to use lapply here to avoid for side effect:

lapply(c("data1","data2","data3"), function(dx){
  dx <- transform(dx,as.Date(x))
})
agstudy
  • 119,832
  • 17
  • 199
  • 261
1

Try

date.columns <- c('date1','date2','date3') # all date columns
df[date.columns] <- lapply(df[date.columns], as.Date)
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
0

For the for loop to evaluate the data frame name (i) and the variable name (x) properly, you need to use [""] notation. Try the following:

for (i in list) {
  i["x"] <- as.Date(i["x"])
}

If this doesn't work post an example of your data using dput() (see How to make a great R reproducible example?)

Community
  • 1
  • 1
Phil
  • 4,344
  • 2
  • 23
  • 33
0

It's an old question but nobody gave the OP a satisfying answer. Here is a similar question

How to use a string to refer to a data frame in R?

Using get and assign

for (i in list) {
  df <- get(i)
  df$X <- as.Date(df$X)
  assign(as.character(i), df, envir= .GlobalEnv)
}

Here you are working with copies

Julien
  • 1,613
  • 1
  • 10
  • 26