Dear Stackoverflow'ers!
I have simple database, app. 130 variables, 1500 records and lots of similar plots to create. I try to avoid save them by hand. The for loop works perfectly for plots (in RStudio).
Here are the data as .csv on dropbox.
data <- read.csv2("data.csv", header=TRUE)
data <- select(data,v1,v2,v3,v4,v5,v6,v7)
for (i in data) {
sjp.frq(i)
}
I would like to save the plots in some directory as a separate .png or .jpg files. I found some clues here. The code looks like this:
data <- select(df,v1,v2,v3,v4,v5,v6,v7)
variables <- names(data)
for (i in data) {
png(paste0("plots/plot_",names(data)[i],".png"))
sjp.frq(i)
dev.off()
}
I deliberately simplified the sjp.frq expression to not make the code unnessecarely complicated.
And here's the problem. I get only single .png file in folder. Where do I make mistake? There should be seven of them.
Best regards, MaciejB.
PS. I follow the suggestion of making code reproducible and added sample of my databaase. When I use i.e. iris, it works. It seems to be something wrong with my data, some NA's maybe? But when I used na.omit() it's the same.
PS.2 I checked another ploting functions like hist() or plot() but it's the same. Only one plot produced and saved.
This works here!
data1 <- read.csv2("~/Temp/data.csv", header=TRUE)
data <- select(data1,v1,v2,v3,v4,v5,v6,v7)
variables <- names(data)
dane=1:length(variables)
for (i in dane ) { #i=2
png(paste0("Temp/plot_",names(data)[i],".png"))
sjp.frq(data[,i],title = names(data)[i])
dev.off()
}
Here 3 of all plots:
Related
new stackoverflow user here, so apologies if this question/context is not up to standard. I welcome feedback.
I have two data frames that I would like to visualize as two separate tables in a PDF report. One of the data frames is a summary table that averages all the more granular level data from the second data frame. I am looking to put the summary table on top of the more granular level table. They are different sizes (different number of rows and columns), so let me know if that is a problem.
As for actual code/process, I am using the "formattable" package to make good looking tables; however I have no idea how to move on from there. I have tried using the grid.arrange function (from gridExtra package) and layout functions - but I get an error for grid.arrange and have not been able to figure out how to use the layout function (even after spending time reviewing other stackoverflow questions). Code is below:
library(formattable)
library(gridExtra)
m1 <- matrix("summary",1,3)
m2 <- matrix("granular",20,5)
t1 <- formattable(data.frame(m1))
t2 <- formattable(data.frame(m2))
layout(t1, t2, nrow=2)
grid.arrange(t1,t2, nrow=2, ncol=1)
for layout function I get the following error:
Error in layout(t1, t2, nrow = 2) : unused argument (nrow = 2)
and for grid.arrange i am getting the error:
Error in `$<-.data.frame`(`*tmp*`, "wrapvp", value = list(x = 0.5, y = 0.5, :
replacement has 17 rows, data has 1
Finally, as for the exporting to PDF part, I have not been able to even export ONE of the formattable class data frames, so I have no idea how I would export the both of them to a PDF. It appears in my working directory and also appears on the Plots window in RStudio, but it says: "There was an error opening this document. This file is already open or in use by another application." So I figure the file didn't process correctly. Using:
pdf("SamplePDF.pdf", width=11, height=8)
formattable(data.frame(m1))
dev.off()
I am doing this in R because I am taking advantage of the features of the "formattable" package and mean to eventually use the "RDCOMClient" to send these reports out automatically by email. Plus, SQL and R are basically the only "code" I know.
Thank you, and apologies in advance for a first-time poster!
grid.arrange and the other commands in the gridExtra package accepts grobs, so one option is to make your tables into table grobs with the tableGrob command. If you go this route though you are no longer in the formattable universe, though from this example its not clear that you need any of its special features.
library(gridExtra)
m1 <- matrix("summary",1,3)
m2 <- matrix("granular",20,5)
tg1 <- tableGrob(m1)
tg2 <- tableGrob(m2)
grid.arrange(tg1,tg2, nrow=2, ncol=1)
Then proceed to export to pdf. Hope that helps.
Something like this works for me:
pdf('test00.pdf')
grid.table(t1)
grid.newpage()
grid.table(t2)
dev.off()
Although this forces different tables to be on different pages.
I through assign() function to name many data frame.
Use this script:
> for (i in 1:15)
{
assign(paste0('TagIDNum',i),filter(Ordf,Ordf$TagID==i))
}
Got this 15 data frame
Next step I need to output scatterplot of these 15 data frames with pairs() function and for loop to output pdf in once.
Here is my script:
for (i in 1:15)
{
pdf(paste('TagPlotNum',j,'.pdf',sep=''))
x<-paste('TagIDNum',j,sep='')
print(pairs(~x[,11]+x[,38]+x[,39]+x[,40]+x[,41]+x[,43]))
dev.off()
}
But I got this error information
Error information: incorrect number of dimensions
And I found that the x had no data, just a value as follow:
I will do some analysis in next steps, so this problem disturb for 2 days.
Post this article to ask any expert to solve this issue.
In my opinion, maybe paste() function have something to think, but I don't know how to solve this topic.
Here is my R information:
Thanks.
As per your output, x is the string "TagIDNum11", not the object with that name. You can get that however using get(), i.e.
x<-get(paste('TagIDNum',j,sep=''))
FYI, spaces are free, your code will be much more readable if you use them, i.e.
x <- get(paste('TagIDNum', j, sep=''))
This is very elementary for those who use R... (But I do stats with Stata and Mplus.)
I develop many plots (638 in total) and want to save all in separate files. It worked well first, not now
for(i in 001:638){
## command for plot comes here, including mentioning of i ##
dev.copy(png,'plot-%d.png')
dev.off()
}
I want one file for each plot, but end up with a single plot file (plot_1.png), with only the last plot.
Christopher
png function will do this by default. For example, this will create 10 plots in your working directory.
png("plot-%d.png")
for(i in 1:10) plot(1:i)
dev.off()
You'll want to use one of the paste() functions to create your string.
Since you didn't provide a reproducible example I can only guess, but I think that something like this would probably work.
paste("plot",i,".png", sep = "")
in place of your current use of c style % replacement. So this
for(i in 001:638){
#command for plot comes here, including mentioning of i ##
dev.copy(png,paste("plot",i,".png", sep = ""))
dev.off()
}
I am trying to create a loop in R that does the following. I have a map with for example 10 datasets: file1.txt.csv, file2.txt.csv, etc. Now I simply want to create one graph per data set and output that, so that I get file1.jpeg, file2.jpeg, etc.
This is what I got so far:
fileNames <- Sys.glob("*.txt.csv")
for (fileName in fileNames) {
VolumeData <- read.delim(fileName, header = FALSE)
# convert data frame to data table
VolumeDatat <- VolumeData [, -(7:14)]
# set column names
setnames(VolumeDatat, c("MCS", "cell_type", "cell_number", "total_volume"))
jpeg(sub(".txt.csv",".jpg"))
plot(VolumeDatat$total_volume~VolumeDatat$MCS,type="l")
dev.off()
}
And I guess that
jpeg (sub(".txt.csv",".jpg"))
is the essential part for this, but I can't figure this out, also the arguments for jpeg in the library didn't help me much further.
First, I tried with jpeg (fileName.jpeg), which works, but only for the last file in the loop as the file gets overwritten for each time you run the script, e.g. each file.
So now I tried it with some sub-function, cause I thought that might work, but by doing so, I got:
Error in sub(".txt.csv", ".jpg") :
argument "x" is missing, with no default
Could anyone help me with this? I'd be very grateful!
I have the following problem, please.
I need to read recursively raster images, stack and store them in a file with different names (e.g. name1.tiff, name2.tiff, ...)
I tried the following:
for (i in 10) {
fn <- system.file ("external / test.grd", package = "raster")
fn <-stack (fn) # not sure if this idea can work.
fnSTACK[,, i] <-fn
}
here expect a result of the form:
dim (fnSTACK)
[1] 115 80 10
or something like that
but it didn't work.
Actually, I have around 300 images that I have to be store with different names.
The purpose is to extract time series information (if you know another method or suggestions I would appreciate it)
Any suggestions are welcomed. Thank you in advance for your time.
What I would first do is put all your *.tiff in a single folder. Then read all their names into a list. Stack them and then write a multi-layered raster. I'm assuming all the images have the same extent and projection.
### Load necessary packages
library(tiff)
library(raster)
library(sp)
library(rgdal) #I cant recall what packages you might need so this is probably
library(grid) # overkill
library(car)
############ function extracts the last n characters from a string
############ without counting the last m
subs <- function(x, n=1,m=0){
substr(x, nchar(x)-n-m+1, nchar(x)-m)
}
setwd("your working directory path") # you set your wd to were all your images are
filez <- list.files() # creates a list with all the files in the wd
no <- length(filez) # amount of files found
imagestack <- stack() # you initialize your raster stack
for (i in 1:no){
if (subs(filez[i],4)=="tiff"){
image <- raster(filez[i]) # fill up raster stack with only the tiffs
imagestack <- addLayer(imagestack,image)
}
}
writeRaster(imagestack,filename="output path",options="INTERLEAVE=BAND",overwrite=TRUE)
# write stack
I did not try this, but it should work.
Your question is rather vague and it would have helped if you had provided a full example script such that it could be more easily understood. You say you need to read several (probably not recursively?) raster images (files, presumably) and create a stack. Then you need to store them in files with different names. That sounds like copying the files to new files with a different names, and there are R functions for that, but that is probably not what you intended to ask.
if you have a bunch of files (with full path names or in the working directory), e.g. from list.files()
f <- system.file ("external/test.grd", package = "raster")
ff <- rep(f, 10)
you can do
library(raster)
s <- stack(ff)
I am assuming that you simply need this stack for operations in R (it is an object, but not a file). You can extract the values in many ways (see the help files and vignette of the raster package). If you want a three dimensional array, you can do
a <- as.array(s)
dim(a)
[1] 115 80 10
thanks "JEquihua" for your suggestion, just need to add the initial variable before addLayer ie:
for (i in 1:no){
if (subs(filez[i],4)=="tiff"){
image <- raster(filez[i]) # fill up raster stack with only the tiffs
imagestack <- addLayer(imagestack,image)
}
}
And sorry "RobertH", I'm newbie about R. I will be ask, more sure or exact by next time.
Also, any suggestions for extracting data from time series of MODIS images stacked. Or examples of libraries: "rts ()", "ndvits ()" or "bfast ()"
Greetings to the entire community.
Another method for stacking
library(raster)
list<-list.files("/PATH/of/DATA/",pattern="NDVI",
recursive=T,full.names=T)
data_stack<-stack(list)