首页 > 解决方案 > 更改多个数据框中的变量类型

问题描述

我有几个具有不同名称和相同日期变量的数据框。我想将变量的类型更改为yearmon. 我试图创建包含所有数据框的列表并更改类型,但我不能unlist按原样处理数据。尝试了本站所有代码,但总是有一些错误。我认为就我而言,我必须通过循环来解决这个问题。

这是到目前为止的代码:

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 
  }
}

这是我为列表中的数据框尝试的代码。

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

它返回日期的 NA。

标签: rloops

解决方案


我们可以做到(注意:在使用此解决方案之前,您需要在形成数据集或将日期转换为字符时设置stringsAsFactorsFALSE,见下文):

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

结果:

[[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

数据:

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)

推荐阅读