Dealing with repetitive tasks in R

后端 未结 3 744
春和景丽
春和景丽 2020-12-28 17:35

I often find myself having to perform repetitive tasks in R. It gets extremely frustrating having to constantly run the same function on one or more data structures over and

3条回答
  •  没有蜡笔的小新
    2020-12-28 18:11

    If the names are similar you could iterate over them using the pattern argument to ls:

    for (i in ls(pattern="df")){
      assign(paste("t",i,sep=""),na.omit(get(i)))
    }
    

    However, a more "R" way of doing it seems to be to use separate environment and eapply:

    # setup environment
    env <- new.env()
    
    # copy dataframes across (using common pattern)
    for (i in ls(pattern="df")){
      asssign(i,get(i),envir=env)
      }
    
    # apply function on environment
    eapply(env,na.omit)
    

    Which yields:

    $df3
         Region variable value
    1      Asia     2006   300
    2    Africa     2006   200
    3    Europe     2006   200
    4 N.America     2006   500
    5 S.America     2006   300
    
    $df2
         Region variable value
    1      Asia     2005    55
    2    Africa     2005   350
    3    Europe     2005    40
    4 N.America     2005    90
    5 S.America     2005    99
    
    $df1
         Region variable value
    1      Asia     2004    35
    2    Africa     2004    20
    3    Europe     2004    20
    4 N.America     2004    50
    5 S.America     2004    30
    

    Unfortunately, this is one huge list so getting this out as seperate objects is a little tricky. Something on the lines of:

    lapply(eapply(env,na.omit),function(x) assign(paste("t",substitute(x),sep=""),x,envir=.GlobalEnv))
    

    should work, but the substitute is not picking out the list element names properly.

提交回复
热议问题