r - 更改多个数据框中的变量类型
问题描述
我有几个具有不同名称和相同日期变量的数据框。我想将变量的类型更改为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。
解决方案
我们可以做到(注意:在使用此解决方案之前,您需要在形成数据集或将日期转换为字符时设置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)
推荐阅读
- angular - Angular Material Stepper not working on StackBlitz
- c# - 当我单击按钮转到 winforms 中的另一个表单时,应用程序冻结
- java - 打开新的命令提示符并从在命令提示符中运行的 Java 程序发送命令
- c# - MvvmCross 6.0:如何在初始化时将参数传递给 App?
- blockchain - 如何以编程方式部署和验证(公共源代码)以太坊智能合约?
- google-chrome-extension - 获取标签 URL,复制到新标签,更改域中的某些内容
- c# - .NET 如何通过 Windows 虚拟 COM 端口连续发送和接收 600k 字节块?
- wordpress - wordpress 中每种语言都需要一个 dmscookie 代码
- reactjs - 如何测试动态反应组件
- r - 更改每行中出现 80% 次的变量的值,R