将数据帧添加为列表元素(使用for循环) [英] Adding data frames as list elements (using for loop)

查看:91
本文介绍了将数据帧添加为列表元素(使用for循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的环境中有一系列称为EOG的数据框。 2006年至2012年期间每年有一个。像EOG2006,EOG2007 ... EOG2012。我想将它们添加为列表的元素。



首先,我想知道这是否可行。我读了官方的R指南和一些R编程手册,但我没有找到明确的例子。



其次,我想使用一个循环。不幸的是,我曾经做过这个工作的代码是错误的,我正在疯狂地解决它。

  for(j in 2006 :$ {
z< -j
sEOG< -paste(EOG,z,sep =)
dEOG< --get(paste(EOG,z,sep =))
lsEOG< -list()
lsEOG [[sEOG]]< -dEOG
}

这将返回一个包含单个元素的列表。有人可以告诉错误在哪里?



感谢您的帮助!

解决方案

您将继续重新初始化列表。您需要将 lsEOG< -list()之外循环。

  lsEOG< -list()

for(j in 2006:2012){
z < - j
sEOG< - paste(EOG,z,sep =)
dEOG< - get(paste(EOG,z,sep =))
lsEOG [[sEOG] ]< -dEOG
}

此外,您可以使用 j 直接在中粘贴函数:

  sEOG<  -  paste(EOG,j,sep =)


I have in my environment a series of data frames called EOG. There is one for each year between 2006 and 2012. Like, EOG2006, EOG2007...EOG2012. I would like to add them as elements of a list.

First, I am trying to know if this is possible. I read the official R guide and a couple of R programming manuals but I didn't find explicit examples about that.

Second, I would like to do this using a for loop. Unfortunately, the code I used to do the job is wrong and I am going crazy to fix it.

for (j in 2006:2012){
z<-j
sEOG<-paste("EOG", z, sep="")
dEOG<-get(paste("EOG", z, sep=""))
lsEOG<-list()
lsEOG[[sEOG]]<-dEOG
}

This returns a list with one single element. Can someone please tell where is the mistake?

Thank you for your help!

解决方案

You keep reinitializing the list inside the loop. You need to move lsEOG<-list() outside the for loop.

lsEOG<-list()

for (j in 2006:2012){
  z <- j
  sEOG <- paste("EOG", z, sep="")
  dEOG <- get(paste("EOG", z, sep=""))
  lsEOG[[sEOG]] <-dEOG
}

Also, you can use j directly in the paste functions:

sEOG <- paste("EOG", j, sep="")

这篇关于将数据帧添加为列表元素(使用for循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆