pasting Jpeg output in directory in R - 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.

Related

R function stops after system() call

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.

R: Iterating Over the List

I am trying to implement following algorithm in R:
Iterate(Cell: top)
While (top != null)
Print top.Value
top = top.Next
End While
End Iterate
Basically, given a list, the algorithm should break as soon as it hits 'null' even when the list is not over.
myls<-list('africa','america south','asia','antarctica','australasia',NULL,'europe','america north')
I had to add a for loop for using is.null() function, but following code is disaster and I need your help to fix it.
Cell <- function(top) {
#This algorithm examines every cell in the linked list, so if the list contains N cells,
#it has run time O(N).
for (i in 1:length(top)){
while(is.null(top[[i]]) !=TRUE){
print(top)
top = next(top)
}
}
}
You may run this function using:
Cell(myls)
You were close but there is no need to use for(...) in this
construction.
Cell <- function(top){
i = 1
while(i <= length(top) && !is.null(top[[i]])){
print(top[[i]])
i = i + 1
}
}
As you see I've added one extra condition to the while loop: i <= length(top) this is to make sure you don't go beyond the length of the
list in case there no null items.
However you can use a for loop with this construction:
Cell <- function(top){
for(i in 1:length(top)){
if(is.null(top[[i]])) break
print(top[[i]])
}
}
Alternatively you can use this code without a for/while construction:
myls[1:(which(sapply(myls, is.null))[1]-1)]
Check this out: It runs one by one for all the values in myls and prints them but If it encounters NULL value it breaks.
for (val in myls) {
if (is.null(val)){
break
}
print(val)
}
Let me know in case of any query.

Loop works outside function but in functions it doesn't.

Been going around for hours with this. My 1st question online on R. Trying to creat a function that contains a loop. The function takes a vector that the user submits like in pollutantmean(4:6) and then it loads a bunch of csv files (in the directory mentioned) and binds them. What is strange (to me) is that if I assign the variable id and then run the loop without using a function, it works! When I put it inside a function so that the user can supply the id vector then it does nothing. Can someone help ? thank you!!!
pollutantmean<-function(id=1:332)
{
#read files
allfiles<-data.frame()
id<-str_pad(id,3,pad = "0")
direct<-"/Users/ped/Documents/LearningR/"
for (i in id) {
path<-paste(direct,"/",i,".csv",sep="")
file<-read.csv(path)
allfiles<-rbind(allfiles,file)
}
}
Your function is missing a return value. (#Roland)
pollutantmean<-function(id=1:332) {
#read files
allfiles<-data.frame()
id<-str_pad(id,3,pad = "0")
direct<-"/Users/ped/Documents/LearningR/"
for (i in id) {
path<-paste(direct,"/",i,".csv",sep="")
file<-read.csv(path)
allfiles<-rbind(allfiles,file)
}
return(allfiles)
}
Edit:
Your mistake was that you did not specify in your function what you want to get out from the function. In R, you create objects inside of function (you could imagine it as different environment) and then specify which object you want it to return.
With my comment about accepting my answer, I meant this: (...To mark an answer as accepted, click on the check mark beside the answer to toggle it from greyed out to filled in...).
Consider even an lapply and do.call which would not need return being last line of function:
pollutantmean <- function(id=1:332) {
id <- str_pad(id,3,pad = "0")
direct_files <- paste0("/Users/ped/Documents/LearningR/", id, ".csv")
# READ FILES INTO LIST AND ROW BIND
allfiles <- do.call(rbind, lapply(direct_files, read.csv))
}
ok, I got it. I was expecting the files that are built to be actually created and show up in the environment of R. But for some reason they don't. But R still does all the calculations. Thanks lot for the replies!!!!
pollutantmean<-function(directory,pollutant,id)
{
#read files
allfiles<-data.frame()
id2<-str_pad(id,3,pad = "0")
direct<-paste("/Users/pedroalbuquerque/Documents/Learning R/",directory,sep="")
for (i in id2) {
path<-paste(direct,"/",i,".csv",sep="")
file<-read.csv(path)
allfiles<-rbind(allfiles,file)
}
#averaging polutants
mean(allfiles[,pollutant],na.rm = TRUE)
}
pollutantmean("specdata","nitrate",23:35)

Concatenate variables in R

I want to create an object in R, which will contain one string, with a few variables (in my case it is file path). When I try to use paste to concatenate the file paths I can see only one last variable instead of all variables in one string. I use next code:
for(i in seq_len(nrow(samples))) {
lib = samples$conditions[i]
txtFile = file.path(lib, "hits.txt")
testfiles = paste(txtFile, sep = ',')
}
print(testfiles)
and get something like
cond/hits.txt,
instead of
cond/hits.txt,cond1/hits.txt,cond2/hits.txt and so on
Thank you very much for help

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)
}

Resources