在多个数据框中更改变量类型

时间:2019-07-04 16:37:28

标签: r loops

我有几个具有不同名称和相同日期变量的数据框。我想将变量的类型更改为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。

1 个答案:

答案 0 :(得分:2)

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

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)