I'm trying to run a script to check if a file or dataframe exists, and if it doesn't, to make a call to download the data and save the dataframe. The issue is that when the script tries to create the dataframe after the "else" statement in the code below, it either throws an error or doesn't name the dataframe properly.
Here's the full script:
> for (n in surveys) {
+ dataf <- sub("sg_(.+)","\\1d",n)
+ datafile <- sub("sg_(.+)","\\1d.Rda",n)
+ if ( exists( dataf ) == 1 | file.exists( datafile ) == 1) {print(paste("Skipped datapull for ",dataf," because it already exists.")) }
+ else {dataf <- # There's the problem line
pullsg(eval(as.name(n)),sg_APIkey,sg_secret, verbose = TRUE, var_name_append = TRUE,); # This pullsg() function seems to work fine)
+ save(eval(as.name(dataf)), file=datafile) }
+ }
For example, given n = "sg_student_assent", my desired outcome for the beginning of the "else" statement is this:
"student_assentd" <- pullsg(...)
But the actual outcome is this:
"dataf" <- pullsg(...)
When I try all the ways I know to have R return the value of the string assigned to dataf, they all give me errors. List below:
as.name(dataf) <- pullsg(...)
eval(as.name(dataf)) <- pullsg(...)
deparse(substitute(dataf)) <- pullsg(...)
substitute(dataf) <- pullsg(...)
All of them return a "could not find function" error, for example:
Error in deparse(substitute(dataf)) <- pullsg(eval(as.name(n)), sg_APIkey, :
could not find function "deparse<-"
Error in as.name(dataf) <- pullsg(eval(as.name(n)), sg_APIkey, sg_secret, :
could not find function "as.name<-"
Error in as.symbol(dataf) <- pullsg(eval(as.name(n)), sg_APIkey, sg_secret, :
could not find function "as.symbol<-"
When I use the substitution directly instead of the "dataf" variable it returns this error:
Error in sub("sg_(.+)", "\\1d", n) <- pullsg(eval(as.name(n)), sg_APIkey, :
target of assignment expands to non-language object