r function/loop to add column and value to multiple dataframes

前端 未结 3 1157
终归单人心
终归单人心 2020-12-20 02:46

I have 8 data frames that I want to add a column called \'park\', then fill this column in w/ a value that comes from the last four characters of the data

相关标签:
3条回答
  • 2020-12-20 03:25

    I would put the data.frames in a named list and perform this task:

    rslt <- list(water_land_by_ownname_apis = water_land_by_ownname_apis, 
                 water_land_by_ownname_indu = water_land_by_ownname_indu)
    
    for (i in names(rslt)) {
      col <- unlist(strsplit(i, "_"))[5]
      rslt[[i]]$park <- col
    }
    
    do.call("rbind", rslt)
    
    0 讨论(0)
  • 2020-12-20 03:31

    A variation using Map and some "[<-" trickery:

    vars <- ls(pattern="water_.")
    l <- mget(vars)
    names(l) <- substr(vars,nchar(vars)-3,nchar(vars))
    do.call(rbind,Map("[<-",l,TRUE,"park",names(l)))
    
    0 讨论(0)
  • 2020-12-20 03:32

    You can do this for example:

    do.call(rbind,lapply(ls(pattern='water.*'),
           function(x) {
             dat=get(x)
             dat$park = sub('.*_(.*)$','\\1',x)
             dat
           }))
    
    1. ls will extract all data.frames names having certain pattern, here I assume you data.frame begin with the word water. This will be store names in a list handy for lapply use.
    2. sub will extract the last part of the name
    3. do.call+ rbind applied to the resulted list to get a unique big data.frame

    using your 2 data.frames I get :

                                  OWNERNAME      WATER       LAND park
    1                  Forest Service (USFS)     696600  258642900 apis
    2        Fish and Wildlife Service (FWS)       9900     997200 apis
    3  State Department of Natural Resources    1758600   41905800 apis
    4                      Private Landowner      26100    2536200 apis
    5            National Park Service (NPS)  112636800  165591900 apis
    6                                Unknown 1586688300 1075917600 apis
    7                    Private Institution          0     461700 apis
    8                   Native American Land   11354400  314052300 apis
    12          The Nature Conservancy (TNC)      24300     719100 indu
    21                      Other State Land    1018800   10045800 indu
    31                   Private Institution    5282100   12556800 indu
    41    State Department of Transportation          0        900 indu
    51 State Department of Natural Resources      12600    2018700 indu
    61                               Unknown   19192500 1446426000 indu
    71           National Park Service (NPS)     802800   42484500 indu
    
    0 讨论(0)
提交回复
热议问题