[英]R - Loop over several files
I want to apply this code on several lists of dataframes (df). 我想将此代码应用于多个数据帧(df)列表。
df1<- lapply(df1, function(x) {
x$Date <- as.Date((x$Date), format="%Y-%m-%d")
x})
The dataframe lists are called df1
, df2
, df3
, df4
and abc1
, abc2
, abc3
, abc4
. 数据帧列表称为
df1
, df2
, df3
, df4
和abc1
, abc2
, abc3
, abc4
。 The Date-column is always on the same place. 日期列始终位于同一位置。
I tried this to get the df1-4
done, but it doesn't work. 我尝试这样做以完成
df1-4
,但不起作用。
for (i in 1:4) {
df[i] <- lapply(df[i], function(x) {
x$Date <- as.Date((x$Date), format="%Y-%m-%d")
x})}
I also thought about getting all the filenames into a list and looping with that: 我还考虑过将所有文件名放入列表中并以此循环:
df_list = c("df1","df2", "df3", "df4", "abc1", "abc2", "abc3", "abc4")
But I haven't succeeded with that. 但是我还没有成功。 I want to keep the original names of the files.
我想保留文件的原始名称。 Any suggestions?
有什么建议么?
for(i in 1:length(df_list)) {
df_list[[i]] <- lapply(df_list[[i]], function(x) {
x$Date <- as.Date((x$Date), format="%Y-%m-%d")
x})
}
Does this work for you? 这对您有用吗?
For me it does: 对我而言:
class(df_list[[1]][[1]]$Date)
[1] "Date"
Your error seemed to happen because you used []
instead of [[]]
. 由于使用了
[]
而不是[[]]
因此似乎发生了错误。 You have to use double brackets to refer to the data.frame. 您必须使用双括号来引用data.frame。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.