Essi
Essi

Reputation: 801

R Loop code over several lists of dataframes

I have several lists of dataframes and I want to format the date in each single dataframe within all lists of dataframes. Here is an example code:

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,7, length = 5)
v4 = seq(-6,3, length = 5)

df1 = data.frame(Date = v1, df1_Tmax = v2, df1_Tmean = v3, df1_Tmin = v4)
dfl1 <- list(df1, df1, df1, df1)
names(dfl1) = c("ABC_1", "DEF_1", "GHI_1", "JKL_1")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(3,21, length = 5)
v3 = seq(-3,8, length = 5)
v4 = seq(-7,4, length = 5)

df2 = data.frame(Date = v1, df2_Tmax = v2, df2_Tmean = v3, df2_Tmin = v4)
dfl2 <- list(df2, df2, df2, df2)
names(dfl2) = c("ABC_2", "DEF_2", "GHI_2", "JKL_2")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(4,22, length = 5)
v3 = seq(-4,9, length = 5)
v4 = seq(-8,5, length = 5)

df3 = data.frame(Date = v1, df3_Tmax = v2, df3_Tmean = v3, df3_Tmin = v4)
dfl3 <- list(df3, df3, df3, df3)
names(dfl3) = c("ABC_3", "DEF_3", "GHI_3", "JKL_3")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,8, length = 5)
v4 = seq(-6,3, length = 5)

abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

abclist <-list(abc, abc, abc, abc)

names(abclist) = c("ABC_abc", "DEF_abc", "GHI_abc", "JKL_abc")

I know how to change the date-column manually:

dfl1$ABC_1$Date = as.Date(dfl1$ABC_1$Date,format="%Y-%m-%d")
class(dfl1$ABC_1$Date)

But how can I do that for each single Date-Column in all of my lists of dataframes?

Upvotes: 1

Views: 70

Answers (2)

A. Suliman
A. Suliman

Reputation: 13125

Here is one option using get and assign

nms <- c('dfl1', 'dfl2', 'dfl3', 'abclist')
lapply(nms, function(x) assign(x,lapply(get(x), 
                                 function(y) {y$Date1 <- as.Date(y$Date, format="%Y-%m-%d") 
                                 return(y)}), 
                        envir = .GlobalEnv))

PS: Be careful with assign since it will change your global environment .GlobalEnv. Many R users will suggest the list solution over assign.

Upvotes: 2

kath
kath

Reputation: 7724

This can be done with lapply:

lapply(dfl1, function(x) {
  x$Date <- as.Date(x$Date, format="%Y-%m-%d") 
  return(x)})

If you want to do this for all of you df-lists you need to store them in a list and then you can use a slightly modified version of the above call:

df_list <- list(dfl1, dfl2, dfl3, abclist)

lapply(df_list, function(x) {
  x[[1]]$Date <- as.Date(x[[1]]$Date, format="%Y-%m-%d") 
  return(x)})

This assumes that the Date-column has always the same name "Date".

Upvotes: 2

Related Questions