this.year<-2014
x<-this.year-1
y<-this.year-2
x.s<-x-2000
y.s<-y-2000
tpop_y.s<-acs.fetch(endyear=x,span=1,geography=mystates,variable="B01003_001", col.names="DM_TPOP_x.s")
tpop_x.s<-acs.fetch(endyear=y,span=1,geography=mystates,variable="B01003_001",col.names="DM_TPOP_y.s")
I'm using the package acs
to pull out data from the American community survey to update an infographics website. I hope to run the code every year by inputing the current year in this.year
and having the code update data for the past 2 years, x
and y
.
If this.year
is 2015, x
is 2014, xs
is 14, y
is 2013, ys
is 13. The end result I want is (for y) the data frame name tpop_13
with the column name DM_TPOP_13
. (for x) the data frame name tpop_14
with the column name DM_TPOP_14
.
The code is pulling the desired data correctly, but this code returns (for y) the data frame name tpop_y.s
with the column name DM_TPOP_y.s
. (for x) the data frame name tpop_x.s
with the column name DM_TPOP_x.s
. I tried searching for similar questions and found this one: How to print R variables in middle of String
I tried applying the answer by using the quotes \\"',xs,'\\"
to solve my problem, but it doesn't work. The code returns (for x) the column name DM_TPOP_...xs..
. I understand that R does not evaluate any expression within the quotes - it just prints the string you defined. But how can you get around this problem so that there can be a variable in a string?
Help would be greatly appreciated!
You can use functions like paste
, paste0
, and sprintf
to construct strings from string constants and variables. There is also functionality in the gsubfn package to do Perl like string interpolation.
Here is how you can work: store the data in the list kk
, so that first element , kk[[1]]
or kk[["tpop_13"]]
, gives the data for 2013 and second element, kk[[2]]
or kk[["tpop_12"]]
gives the data for 2012, with the name of each element as you suggested.
wa=geo.make(state="WA")
kk<-lapply(c(x,y),function(i){
acs.fetch(endyear=i,span=1,geography=wa,variable="B01003_001", col.names=paste0("DM_TPOP_",i-2000))
})
names(kk)<-paste0("tpop_",c(x-2000,y-2000))
kk
$tpop_13
ACS DATA:
2013 ;
Estimates w/90% confidence intervals;
for different intervals, see confint()
DM_TPOP_13
Washington 6971406 +/- 0
$tpop_12
ACS DATA:
2012 ;
Estimates w/90% confidence intervals;
for different intervals, see confint()
DM_TPOP_12
Washington 6897012 +/- 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.