Mar
Mar

Reputation: 147

Change variables type in multiple data frames

I have several data frames with different names and same date variable. I want to change the type of the variable to yearmon. I've tried to create list with all data frames and change the type, but I can't unlist the data as it was. Tried all codes in this site, but there's always some error. I think in my case I have to approach this with loop.

This is the code so far:

df=data.frame(date=c("201101","201102","201103"),value=c(3,4,6))
df2=data.frame(date=c("201101","201102","201103"),value=c(3,4,6))
df3=data.frame(date=c("201101","201102","201103"),value=c(3,4,6))

library(zoo)

# list of all impoted dataframes
files <- ls()[sapply(mget(ls(), .GlobalEnv), is.data.frame)] 

for (i in files){        #search for the dataframe name                                                       
  for (j in length(get(i)[,1])){   #get the length of current data frame
  d[j]=get(i)[j,1]     #gets current data frame’s Date_col (the column with date)
  d[j] <- as.yearmon(as.character(d[j,]), "%Y%m") #convert 
  assign(get(i)[j,1],d[j])  # an error shows here 
  }
}

This is the code that I tried for dataframes in list.

l.df <- lapply(ls(), function(x) if (class(get(x)) == "data.frame")
get(x))
files <- ls()[sapply(mget(ls(), .GlobalEnv), is.data.frame)]
names(l.df) <-  files

lapply(l.df, transform, date=as.yearmon(as.character(date, "%Y%m")))

It returns NA for date.

Upvotes: 0

Views: 253

Answers (1)

NelsonGon
NelsonGon

Reputation: 13319

We can do(Note: You need to set stringsAsFactors to FALSE while forming your data sets or convert date to character before using this solution, see below):

lapply(my_list ,
       function(x) 
       transform(x, 
                 date=zoo::as.yearmon(anytime::anydate(x$date))))

Result:

[[1]]
      date value
1 Jan 2011     3
2 Feb 2011     4
3 Mar 2011     6

[[2]]
      date value
1 Jan 2011     3
2 Feb 2011     4
3 Mar 2011     6

[[3]]
      date value
1 Jan 2011     3
2 Feb 2011     4
3 Mar 2011     6

Data:

df=data.frame(date=c("201101","201102","201103"),value=c(3,4,6),
              stringsAsFactors = F)
df2=data.frame(date=c("201101","201102","201103"),value=c(3,4,6),
               stringsAsFactors = F)
df3=data.frame(date=c("201101","201102","201103"),value=c(3,4,6),
               stringsAsFactors = F)

Upvotes: 2

Related Questions