[英]Unlist lists of dataframes and assign names on a loop - R
I need to unlist several lists of dataframes whilst conserving and adapting their names.我需要取消列出几个数据框列表,同时保存和调整它们的名称。
Each dataframe needs to be labelled with the respective date.每个数据框都需要标有各自的日期。
As in如
`Data_2021-05-07`$df1
`Data_2021-05-08`$df1
`Data_2021-05-09`$df1
...
`Data_2021-05-29`$df1
`Data_2021-05-30`$df1
`Data_2021-05-31`$df1
Here's what I got这是我得到的
May <- c("07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31")
for (i in May){
Date <- paste("2021-05", i, sep = "-")
List <- noquote(paste("`Data_", Date, "`", sep = ""))
File <- parse(noquote(paste(List, "$df1", sep = "")))
DfName <- paste("df1", Date, sep = "_")
assign(DfName, File)
}
When I run that code I get the following code I get this error:当我运行该代码时,我收到以下代码我收到此错误:
cannot open file '`Data_2021-05-07`$df1': No such file or directoryError in file(filename, "r") : cannot open the connection
I know the error stems from我知道错误源于
File <- parse(noquote(paste(List, "$df1", sep = "")))
However, not only can I see it in my global environment, when I run:但是,不仅可以在我的全局环境中看到它,当我运行时:
`Data_2021-05-07`$df1
I get the intended result.我得到了预期的结果。
Would appreciate any insight into what is wrong with my code.希望能深入了解我的代码有什么问题。
We can use get
to get the value of the data我们可以使用
get
来获取数据的值
for (i in May){
Date <- paste("2021-05", i, sep = "-")
List <- paste0("Data_", Date)
File <- get(List)[["df1"]]
DfName <- paste("df1", Date, sep = "_")
assign(DfName, File)
}
Another option is to use mget
to return all objects in a list
, loop over the list
with lapply
, extract the 'df1' (it is recommended to keep it in a list
instead of creating multiple objects), but if we need objects, use list2env
另一种选择是使用
mget
返回list
所有对象,使用lapply
循环遍历list
,提取“df1”(建议将其保留在list
而不是创建多个对象),但如果我们需要对象,请使用list2env
lst1 <- lapply(mget(paste0("Data_2021-05-", May)), `[[`, "df1")
names(lst1) <- paste0("df1", names(lst1))
list2env(lst1, .GlobalEnv)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.