R- Referencing different dataframes in a loop

后端 未结 3 872
清酒与你
清酒与你 2021-01-27 02:43

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, Pl

3条回答
  •  爱一瞬间的悲伤
    2021-01-27 03:04

    Let's say you have data.frames

    Plant1987 <- data.frame(plantID=1:4, x=rnorm(4))
    Plant1988 <- data.frame(plantID=1:4, x=rnorm(4))
    Plant1989 <- data.frame(plantID=1:4, x=rnorm(4))
    

    You could put a $year column in each with

    year <- 1987:1989
    for(yeari in year) {
      eval(parse(text=paste0("Plant",yeari,"$year<-",yeari)))
    }
    
    Plant1987
    #   plantID           x year
    # 1       1  0.67724230 1987
    # 2       2 -1.74773250 1987
    # 3       3  0.67982621 1987
    # 4       4  0.04731677 1987
    # ...etc for other years...
    

    ...and either bind them together into one data.frame with

    df <- Plant1987
    for(yeari in year[-1]) {
      df <- rbind(df, eval(parse(text=paste0("Plant",yeari))))
    }
    
    df
    #    plantID            x year
    # 1        1  0.677242300 1987
    # 2        2 -1.747732498 1987
    # 3        3  0.679826213 1987
    # 4        4  0.047316768 1987
    # 5        1  1.043299473 1988
    # 6        2  0.003758675 1988
    # 7        3  0.601255190 1988
    # 8        4  0.904374498 1988
    # 9        1  0.082030356 1989
    # 10       2 -1.409670456 1989
    # 11       3 -0.064881722 1989
    # 12       4  1.312507736 1989
    

    ...or in a list as

    itsalist <- list()
    for(yeari in year) {
      eval(parse(text=paste0("itsalist$Plant",yeari,"<-Plant",yeari)))
    }
    
    itsalist
    # $Plant1987
    #   plantID           x year
    # 1       1  0.67724230 1987
    # 2       2 -1.74773250 1987
    # 3       3  0.67982621 1987
    # 4       4  0.04731677 1987
    # 
    # $Plant1988
    #   plantID           x year
    # 1       1 1.043299473 1988
    # 2       2 0.003758675 1988
    # 3       3 0.601255190 1988
    # 4       4 0.904374498 1988
    # 
    # $Plant1989
    #   plantID           x year
    # 1       1  0.08203036 1989
    # 2       2 -1.40967046 1989
    # 3       3 -0.06488172 1989
    # 4       4  1.31250774 1989
    

提交回复
热议问题