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
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)
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)))
You can do this for example:
do.call(rbind,lapply(ls(pattern='water.*'),
function(x) {
dat=get(x)
dat$park = sub('.*_(.*)$','\\1',x)
dat
}))
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.sub
will extract the last part of the namedo.call
+ rbind
applied to the resulted list to get a unique big data.frameusing 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