首页 > 解决方案 > 在 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
             |            |                     |
            ...          ...                   ...

标签: rlistdataframefor-loophierarchy

解决方案


推荐阅读