2
votes

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.

4
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
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 vectorsParikshit Sohoni

4 Answers

1
votes

Better to use lapply here to avoid for side effect:

lapply(c("data1","data2","data3"), function(dx){
  dx <- transform(dx,as.Date(x))
})
1
votes

Try

date.columns <- c('date1','date2','date3') # all date columns
df[date.columns] <- lapply(df[date.columns], as.Date)
0
votes

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?)

0
votes

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