R-在循环中引用不同的数据帧 [英] R- Referencing different dataframes in a loop

查看:138
本文介绍了R-在循环中引用不同的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R我是全新的,所以如果我想到这个完全错误的话,可以随意告诉我。我有一系列关于发电厂的进口数据帧,每年都有一个(Plant1987,Plant1988等),我试图将这些数据帧最终结合成一个数据帧。在此之前,我想为每个数据框添加一个年变量。我可以为每个单独的数据框做到这一点,但想要正式化,并一步到位。我知道如何在stata中做到这一点,但我在这里挣扎。

我在想:

  for(y in 1987:2008){
paste(Plant,y,sep =)$ year < - y
}

这不起作用,因为粘贴显然不是正确的功能。有没有一个聪明,快捷的方法来做到这一点?谢谢

解决方案

试试这个..

  year = seq(1987,2008,by = 1)
list_object_names = sprintf(Plant%s,1987:2008)

list_DataFrame = lapply(list_object_names,get)

for(in 1:length(list_DataFrame)){
list_DataFrame [[i]] [,'Year'] = year [i]
}


I am brand new to R so if I'm thinking about this completely wrong feel free to tell me. I have a series of imported dataframes on power plants, one of each year (Plant1987, Plant1988 etc...) that I am trying to combine ultimately into one data frame. Prior to doing so, I'd like to add a "year" variable to each dataframe. I could do this for each individual dataframe, but would like to formalize it and do it in one step. I know how to do it in stata, but I'm struggling here.

I was thinking something along the lines of:

for (y in 1987:2008) {
     paste("Plant",y,sep="")$year <- y
}

which doesn't work because paste is obviously not the right function. Is there a smart, quick way to do this? Thanks

解决方案

Try this ..

year=seq(1987,2008,by=1)
list_object_names = sprintf("Plant%s", 1987:2008)

list_DataFrame = lapply(list_object_names, get)

for (i in 1:length(list_DataFrame ) ){
    list_DataFrame[[i]][,'Year']=year[i]
}

这篇关于R-在循环中引用不同的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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