R function stops after system() call - r

I've written a very easy wrapper around GDAL in R. It utilises a prewritten statement which is passed to system, creating an output, which I then want to read into the R environment again.
It works by creates a temporary directory in the working directory, printing out an ESRI shape file of our area of interest, and then cuts a raster by this, with some preset information.
My problem: after successfully running the system() call and creating the output file, the function stops. It doesn't execute the next call and read the output into the R environment.
gdalwarpwarp <- function(source_file, source_srs, newfilename, reread=TRUE, clean=TRUE, cutline){
#Create tempfolder if it doesn't exist in the working directory.
if (!dir.exists("./tempfolder")){
dir.create("./tempfolder")
}
#Write temporary shape file
terra::writeVector(cutline, filename = "./tempfolder/outline_AOI.shp" , filetype='ESRI Shapefile',overwrite=TRUE)
#Warp!
if(reread==FALSE){
system(paste0("gdalwarp -cutline ./tempfolder/outline_AOI.shp -dstnodata -9999 -s_srs EPSG:3006 ",source_file, " ",paste0("./tempfolder/",newfilename)))
message('warp warped TRUE')
} else if(reread==TRUE){
system(paste0("gdalwarp -cutline ./tempfolder/outline_AOI.shp -dstnodata -9999 -s_srs EPSG:3006 ",source_file, " ",paste0("./tempfolder/",newfilename)))
newfilename <- terra::rast(paste0("./tempfolder/",newfilename))
}
}
This doesn't run:
newfilename <- terra::rast(paste0("./tempfolder/",newfilename))

The function did not return anything. Here is a somewhat improved version of your function. If you want to keep the output it would make more sense to provide a full path, rather then saving it to a temp folder. I also note that you are not using the argument source_srs
gdalwarpwarp <- function(source_file, source_srs, newfilename, reread=TRUE, clean=TRUE, cutline){
#Write temporary shape file
shpf <- file.path(tempdir(), "aoi.shp")
terra::writeVector(cutline, filename = shpf, filetype='ESRI Shapefile',overwrite=TRUE)
outf <- file.path(tempdir(), newfilename)
system(paste0("gdalwarp -cutline shpf -dstnodata -9999 -s_srs EPSG:3006 ",source_file, " ", outf)
if (reread) {
terra::rast(outf)
} else {
message('warp warped TRUE')
invisible(filename)
}
}
I wonder why you don't use terra::resample or terra::project; perhaps preceded or followed by mask (I may not understand the benefit of using cutline.

Related

Converting the argument name of a function into string

I have developed a function which will take a list of files and will do some statistical tests and will generate a excel file. In the last line of function (return object) I want the function will return a excel file with same names as input file names. In my example it will give list_file.xlsx. IF I enter another file let's say tslist_file it should automatically return tslist_file.xlsx. The function is properly working. Suggest me how I code last line of the function so that I can generalise it.
newey<-function(list_files){
tsmom<-do.call(cbind,lapply(list_files,function(x) read_excel(x)[,2]))
tsmom<-xts(tsmom[,1:5],order.by = seq(as.Date("2005-02-01"),length=183,by="months")-1)
names(tsmom)<-c("tsmom121","tsmom123","tsmom126","tsmom129","tsmom1212")
## newey west
newey_west<-function(x){
model<-lm(x~1)
newey_west<-coeftest(model,vcov=NeweyWest(model,verbose=T))
newey_west[c(1,3,4)]
}
## running newey west
cs_nw_full<-do.call(cbind,lapply(tsmom,newey_west))
library(gtools)
p_values<-cs_nw_full[3,]
cs_nw_full[2,]<-paste0(cs_nw_full[2,],stars.pval(p_values))
write.xlsx(cs_nw_full,"list_file.xlsx")
}
Try:
write.xlsx(cs_nw_full, paste0(eval(substitute(list_files)), ".xlsx"))
Edit:
#jeetkamal is absolutely right - you need to use
write.xlsx(cs_nw_full, paste0(deparse(substitute(list_files)), ".xlsx"))
here.
I apologize for the mistake. eval wold only work if list_files was e.g. the name of a file, not a list object.

dump() in R not source()able- output contains "..."

I'm trying to use dump() to save the settings of my analysis so I can examine them in a text editor or reload them at a later date.
In my code I'm using the command
dump(ls(), settingsOutput, append=TRUE)
The file defined by `settingsOutput' gets created, but the larger objects and locally defined functions are truncated. Here's an excerpt from such a file. Note these files are generally on the order of a few kb.
createFilePrefix <-
function (runDesc, runID, restartNumber)
{
...
createRunDesc <-
function (genomeName, nGenes, nMix, mixDef, phiFlag)
{
...
datasetID <-
"02"
descriptionPartsList <-
c("genomeNameTest", "nGenesTest", "numMixTest", "mixDefTest",
"phiFlagTest", "runDescTest", "runIDTest", "restartNumberTest"
...
diffTime <-
structure(0.531, units = "hours", class = "difftime")
dissectObjectFileName <-
function (objectFileName)
{
...
divergence <-
0
Just for reference, here's one of the functions defined above
createFilePrefix <- function(runDesc, runID, restartNumber){
paste(runDesc, "_run-", runID, "_restartNumber-", restartNumber, sep="")
}
Right now I'm going back and removing the problematic lines and then loading the files, but I'd prefer to actually have code that works as intended.
Can anyone explain to me why I'm getting this behavior and what to do to fix it?

Use of variable in Unix command line

I'm trying to make life a little bit easier for myself but it is not working yet. What I'm trying to do is the following:
NOTE: I'm running R in the unix server, since the rest of my script is in R. That's why there is system(" ")
system("TRAIT=some_trait")
system("grep var.resid.anim rep_model_$TRAIT.out > res_var_anim_$TRAIT'.xout'",wait=T)
When I run the exact same thing in putty (without system(" ") of course), then the right file is read and right output is created. The script also works when I just remove the variable that I created. However, I need to do this many times, so a variable is very convenient for me, but I can't get it to work.
This code prints nothing on the console.
system("xxx=foo")
system("echo $xxx")
But the following does.
system("xxx=foo; echo $xxx")
The system forgets your variable definition as soon as you finish one call for "system".
In your case, how about trying:
system("TRAIT=some_trait; grep var.resid.anim rep_model_$TRAIT.out > res_var_anim_$TRAIT'.xout'",wait=T)
You can keep this all in R:
grep_trait <- function(search_for, in_trait, out_trait=in_trait) {
l <- readLines(sprintf("rep_model_%s.out", in_trait))
l <- grep(search_for, l, value=TRUE) %>%
writeLines(l, sprintf("res_var_anim_%s.xout", out_trait))
}
grep_trait("var.resid.anim", "haptoglobin")
If there's a concern that the files are read into memory first (i.e. if they are huge files), then:
grep_trait <- function(search_for, in_trait, out_trait=in_trait) {
fin <- file(sprintf("rep_model_%s.out", in_trait), "r")
fout <- file(sprintf("res_var_anim_%s.xout", out_trait), "w")
repeat {
l <- readLines(fin, 1)
if (length(l) == 0) break;
if (grepl(search_for, l)[1]) writeLines(l, fout)
}
close(fin)
close(fout)
}

Deleting text from .txt file from within R

I have some code which appends text over an existing .txt file , from within R as following :
write("puts 'hellow world '", file = "C:\\Ruby22-x64\\bin\\elt.rb",
append = TRUE, sep = " ")
setwd("C:/Ruby22-x64/bin/")
test<-system("ruby elt.rb",intern=TRUE) # this will return "hellow world" from ruby interpreter
My question is: after appending the .rb file and running it, how can i remove the "puts 'hellow world '" string from the .rb file, and return it to its initial state?
I tried to look for many functions, but couldn't find any function which can undo the write function.
Just found out a wonderful gist that does the Job : https://gist.github.com/mages/1544009
gist:1544009

pasting Jpeg output in directory in R

I have function which performs scatter plot and I want to paste the results(Jpeg images) in D:/output but instead it is pasting in D:/.I want my results to be pasted on D:/output.
Please do help me.
setwd("D:/output")
IDs <- colnames(raw.expression)
for (i in 1:(dim(raw.expression)[2]-1))
{ for( j in i:(dim(raw.expression)[2]) )
{ if (i != j)
{ jpeg(file=paste("/",IDs[i],"gegen",IDs[j],".jpg",sep=""))
correlation <- round(cor(raw.expression[,i],raw.expression[,j]),2)
maximum <- max(log2(raw.expression[,i]))
minimum <- min(log2(raw.expression[,i]))
plot(log2(raw.expression[,i]),log2(raw.expression[,j])
,xlab=IDs[i],ylab=IDs[j],p‌​ch='.'
,text (maximum-2,minimum+0.5
,labels=paste("R = ",correlation,sep=""),pos=4,offset=0))
dev.off()
}
}
}
In the line
jpeg(file=paste("/",IDs[i],"gegen",IDs[j],".jpg",sep=""))
you prepend the filename with a "/" which would indicate that this is an absolute path, starting at the top of the file structure. I'm guessing on windows, this would be the top of the current drive letter, so it is going into D: rather than the current working directory D:/output.

Resources