Reputation: 3775
I'm working with different countries datasets downloaded from OEC's API.
I'm dividing my work in two steps:
For the first part I did run
chile2013_df <- as.data.frame(fromJSON("http://atlas.media.mit.edu/hs92/export/2013/chl/all/show/"))
keep <- c("data.hs92_id", "data.import_val", "data.export_val")
chile2013_df <- chile2013_df[keep]
and that is ok and works, but if I want to create a function, let's say
country_data <- function(COUNTRYCODE, YEAR) {
assign(paste(COUNTRYCODE, YEAR, "_raw", sep=""), as.data.frame(fromJSON(paste("http://atlas.media.mit.edu/hs92/export/",YEAR,"/",COUNTRYCODE,"/all/show/", sep=""))), envir = globalenv());
assign(c("keep"), c("data.hs92_id", "data.import_val", "data.export_val");
assign(paste(COUNTRYCODE, YEAR, "_clean", sep=""), paste(COUNTRYCODE, YEAR, "_raw[keep]", sep=""));
envir = globalenv())
}
Then if I run
country_data("per","2010")
The raw file will be perfect but then per2010_clean
will look as a text "per2010_raw[keep]"
How can I make per2010_raw[keep]
effective? many thanks in advance.
Upvotes: 1
Views: 68
Reputation: 25223
try this:
keep <- c("data.hs92_id", "data.import_val", "data.export_val")
country_data <- function(COUNTRYCODE, YEAR) {
weblink <- paste0("http://atlas.media.mit.edu/hs92/export/",YEAR,"/",COUNTRYCODE,"/all/show/")
rawdat <- as.data.frame(fromJSON(file=weblink))
cleandat <- rawdat[keep]
return(list(raw=rawdat, clean=cleandat))
} #end country_data
Then you can mapply for your pairs of (country, year). Ideally, dont use the country and year in your variable names as it can grow pretty unwieldy and unscalable after a while
#pulling data
alldat <- mapply(function(x, y) list(country_data(x, y)), c("per","chl"), c(2010, 2013))
names(alldat) <- paste0(c("per","chl"), c(2010, 2013))
#accessing data
alldat[["chl2013"]]$raw
alldat[["chl2013"]]$clean
Upvotes: 3
Reputation: 3775
Your approach is useful, thanks. Changing a little of your code I'm getting something closer to what I wanted.
keep <- c("data.hs92_id", "data.import_val", "data.export_val")
country_data <- function(COUNTRYCODE, YEAR) {
weblink <- paste0("http://atlas.media.mit.edu/hs92/export/",YEAR,"/",COUNTRYCODE,"/all/show/")
clean <<- as.data.frame(fromJSON(weblink))[keep]
}
country_data("per", 2010)
Upvotes: -1