【问题标题】:How can I store data frames produced in a loop in a list, to be able to call them by name later?如何将循环中生成的数据帧存储在列表中,以便以后按名称调用它们?
【发布时间】:2019-07-20 10:09:39
【问题描述】:

在一个循环中,我将一个函数应用于数据框的一列。我将此结果存储在我在循环中创建的另一个数据框中。我想将这些创建的数据框存储在一个列表中,以便以后能够调用它们以便能够对它们执行功能。 (例如合并(列表[1],列表[2]))这是非常失败的。

我尝试了各种不同的功能,例如 get、mget,但似乎我犯了一些基本错误。

library(qdap)

for (l in 1:9)
  {
     temp1 <- freq_terms(df[[paste0("col_0", l, sep="")]]) #i perform function freq_terms over the columns col_01, col_02..., col_09 of df

      assign(paste0("freq",l,sep =""),temp1)
#then I store this result in freq1, freq2, freq3....freq9

            dfstm[l] = list ((paste0("freq",l,sep ="")))

 #then I would like to store the resulting data frame from assign into a list, though I am aware here I am only storing characters...
  }

我想做以下事情;

merge(dfstm[1], dfstm[2])

能够获得“WORD”和“FREQ”的合并列表。但是,我得到的唯一结果是“freq1 freq2”,merge 合并字符串而不是对象。

我该如何解决这个问题?非常感谢您的帮助!

这是来自“频率”矩阵的一些示例数据。生产了“l”个。然后将这些名称存储在列表中。

dput(head(freq1,5))
structure(list(WORD = c("manufacturing", "care", "consumer", 
"health", "goods"), FREQ = c(16, 10, 10, 10, 9)), row.names = c(24L, 
8L, 12L, 22L, 20L), class = c("freq_terms", "all_words", "data.frame"
))

【问题讨论】:

  • 在没有数据集样本的情况下进行测试有点困难。请提供一些带有dput(head(df,n)) 的虚拟数据或一些代表您的数据的小数据集。
  • @NelsonGon ,我编辑了问题以包含一些数据。希望对您有所帮助?

标签: r loops dataframe storing-data


【解决方案1】:

只是对您要达到的目标的猜测,但为什么不简单地使用 lapply 呢?

res <- lapply(1:9, function(i){
         temp <- freq_terms(df[[paste0("col_0", i, sep="")]])
         temp}
)

然后您会得到一个列表,其中包含您可以单独访问和合并的元素。

【讨论】:

  • 感谢您的提示,但是,似乎存在语法错误,我无法尝试您的解决方案。错误是“不匹配的开口括号”。我对 apply 系列不熟悉,因此无法弄清楚该放在哪里......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
  • 2021-04-06
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
相关资源
最近更新 更多