r - 在 For-Loop (r) 中将数据帧放入复杂的分层列表
问题描述
我已经创建了一个列表层次结构,现在我正在尝试将数据框放入这些列表中,但我不确定允许我将数据框放入列表中的语法。
基本上我想要实现的是:
PlanetList[["Mars"]][["Mars vs Venus"]]["PlanetDataFrame"] <- CurrentDataFrame
一切顺利,前提是我已经运行了一次循环以使其失败,但仍将数据框应用于CurrentDataFrame
变量以供我处理。
但是在我的for循环中是这样的:
PlanetList[[Planets[i]]][[vsList]]["PlanetDataFrame"] <- CurrentDataFrame
它不会将我的数据表应用到正确的文件夹中,事实上,据我所知,它正在制作一个新的并写入其中。
我不知道要改变什么,但我假设上面的代码行是我问题的症结所在。
这是完整的for循环:
for(i in 1:length(Planets)) {
for(j in 1:length(Planets)) {
#here I create the 'X vs Y' (e.g. Mars vs Venus) variable to
#direct my newly retrieved data frame into the correct sublist
#later on
vsList <- paste0(Planets[i], ' vs ', Planets[j])
#obviously - file path. All good here.
FilePath <- file.path(paste0(SourceDir, '/', Planets[i]))
#get my data frame full of exciting numbers
PlanetDataFrame <- read_delim(file.path(paste0(FilePath, "Correlations_file_for_", Planets[i], '_vs_', Planets[j], '_threshold_0.0.txt')), ' ', trim_ws = TRUE, col_names = FALSE)
#put that data frame in a corresponding list (or not)
PlanetList[[Planets[i]]][[vsList]]["PlanetDataFrame"] <- PlanetDataFrame
}
}
附加问题:这不仅会完全创建一个新列表并忽略我已经创建的列表,而且还会收到以下警告:
number of items to replace is not a multiple of replacement length
我使用以下方法制作了这个列表层次结构:
Planets = c('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune')
DataSets <- c('PlanetDataFrame', 'PlanetMatrix', 'PlanetTable')
PlanetList <- lapply(Planets, function(el_PlanetList_outer) {
## create a list with |Planets| elements
## this we do by creating first an inner list vector(.)
## and the repeating it |Planets| times
ret <- rep(tibble(setNames(vector("list", length(DataSets)),
DataSets)),
length(Planets))
setNames(ret, ## ret has no proper names yet
paste(el_PlanetList_outer, " vs ", Planets))
})
names(PlanetList) <- Planets ## could have been done with setNames as well
str(PlanetList)
我认为指定 'tibble' 而不是 'list' (上图中的第 6 行文本)可以让我在其中放置一个数据框?
我很抱歉,因为这可能已经把这个问题变成了一个不是我最初意图的 hydra。
因此,希望能帮助我的所有信息都在上面列出,并且冒着浪费几百比特的风险:
我想要实现的只是检索这样的文件:
Correlations_file_for_Saturn_vs_Mercury_threshold_0.0.txt
然后将其整齐地弹出到正确的列表/子列表中:
PlanetList > Saturn > Saturn vs Mercury > PlanetDataFrame
我的文件层次结构的缩写视图,显示了第一个行星:
Planet List -
|
|-- Mercury -
| |
| |-- Mercury vs Venus -
| | |
| | |--PlanetDataFrame
| | |
| | |--PlanetMatrix
| | |
| | |--PlanetTable
| | |
... ... ...
解决方案
推荐阅读
- azure - 使用 Azure AD 用户凭据将文件存储共享映射为网络驱动器
- c# - 在 .Net Core 控制台应用程序中同时使用 NLog 和控制台日志记录
- spring-boot - Spring Boot、Thymeleaf 和 CSS
- django - 如何将 Google 日历添加到已经使用 Django-allauth google social login 的 Django Webapp
- java - Admob插页式崩溃并从应用程序中跳出而没有错误
- python - 如何让机器人在 discord.py 中编辑自己的消息
- jquery - 使用 jquery 更改两个 div 元素之一上的文本
- c++ - 数组调整大小,当前有终端错误
- ruby-on-rails - NameError(未初始化的常量 ActiveSupport::ParameterFilter):如何修复
- python - Django 手动渲染表单并使用 csfr 令牌