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)
Related
I have a raster stack named rstack:
rstack <- list.files(path) #path contains the location of the directory
Now I have another raster file named araster.
How do I add this new raster araster into the stack rstack?
I have spent a lot of time searching for this online but to no avail.
Not sure if I'm following your question correctly, but f you are merely want to combine both stacks, it should simply work with c.
rstack <- list.files()
newstack <- list.files()
combined_stack <- c(rstack, newstack)
You can use the addLayer function to add new raster files to an existing stack.
library(raster)
rstack <- addLayer(rstack,araster)
I wanted to do something I thought simple, but... well, I failed repetitively.
I want to create a gif or a video (.avi) from pictures in a folder with R.
I can list the path and the names of the pictures (e.g. "./folder/1.jpg" "./folder/2.jpg" "./folder/3.jpg" "./folder/4.jpg" )
I just wanted to put them the one after the other and create a video or gif file (I will treat them frame by frame later, so the speed is not important)
I found a solution with SaveGIF, it works with plots in R but I didn't find the way to use it with external jpg.
Otherwise, there was this solution with image_animate "Animated graphics", but again, I didn't manage.
Do somebody already have a solution to do that?
Thank you very much for your help!
You can do it with the magick package, which gives you access to ImageMagick functions. For example, if the frames of your movie are in files named
frames <- paste0("folder/", 1:100, ".jpg")
then you would create a movie using
library(magick)
m <- image_read(frames)
m <- image_animate(m)
image_write(m, "movie.gif")
You could choose to write to other formats as well, just by changing the filename, or using other arguments to image_write().
A better solution in my oppinion is using the av package.
example:
list_of_frames <- list.files("your/path/to/directory", full.names=T)
av::av_encode_video(list_of_frames, framerate = 30,
output = "output_animation.mp4")
I am trying to automate the data ingestion process in an R script that pulls data from a directory that updates regularly.
The general framework follows this process
library(sp)
library(rgdal)
library(raster)
f1.t1.cir <- stack("../raster/field1/f1_cir_t1.tif")
f1.t1.NDVI <- stack("../raster/field1/f1_ndvi_t1.tif")
f1.t1.RGB <- stack("../raster/field1/f1_ndvi_t1.tif")
f1.dat <- c(f1.t1.cir, f1.t1.NDVI, f1.t1.RGB)
for (i in f1.dat){
plotRGB(i)
}
I would like to generate each f1.t1.cir type object from the directory directly such that when I add a new TIFF file f1_cir_t2.tif, the r script will create an object f1.cir.t2.
I am trying to use something like
a <- list.files(path= "../raster/field1", pattern = "\\.tif$")
b <- gsub("_", "\\.", a)
for (i in a) {
assign(get(b[(which(a==i))]), stack((paste("../raster/field1/", i,sep=""))))
}
At this point, I would have all tiff files as stacked multiband raster objects in the R workspace.
I am getting the following error,
Error in get(b[(which(a == i))]) : object 'f1_t1_DSM.tif' not found
I can not figure out if this is a get() problem, or something else.
for reference
> a
[1] "f1_t1_DSM.tif" "f1_t1_NDVI.tif"
> b
[1] "f1.t1.DSM.tif" "f1.t1.NDVI.tif"
so that much is working, I think.
Any suggestions?
#joran, great suggestion...
f1.t1<-list()
for(i in list.files(path= "../raster/field1", pattern = "\\.tif$")){
f1.t1[[i]]<-stack((paste("../raster/field1/", i, sep="")))
}
Worked very well, no need to change the names.
Thank you.
I am trying to write an R function that can loop through 300 .csv files and calculate the mean of columns. Can someone give me high level guidance on how to do this? All the files are in the same directory and have the same column headings. The mechanics of it shouldn't be that hard, but I am having a hard time finding enough documentation on R syntax to do this. Please help. Thank you.
There are a few ways to load files into R, but probably the easiest is using the list.files function. Your code would look something like this:
setwd("") # set to your directory
files <- list.files() #load the file names into the workspace
for(i in sequence(length(files))){
yourData <- read.scv(files[i])
yourMeans <- apply(yourData, 1, mean)
#save your means in some meaningful way from each csv.
}
I am working with very large data layers for a SDM class and because of this I ended up breaking some of my layers into a bunch of blocks to avoid memory restraint. These blocks were written out as .grd files, and now I need to get them read back into R and merged together. I am extremely new to R an programming in general so any help would be appreciated. What I have been trying so far looks like this:
merge.coarse=raster("coarseBlock1.grd")
for ("" in 2:nBlocks){
merge.coarse=merge(merge.coarse,raster(paste("coarseBlock", ".grd", sep="")))
}
where my files are in coarseBlock.grd and are sequentially numbered from 1 to nBlocks (259)
Any feed back would be greatly appreciated.
Using for loops is generally slow in R. Also, using functions like merge and rbind in a for loop eat up a lot of memory because of the way R passes values to these functions.
A more efficient way to do this task would be to call lapply (see this tutorial on apply functions for details) to load the files into R. This will result in a list which can then be collapsed using the rbind function:
rasters <- lapply(list.files(GRDFolder), FUN = raster)
merge.coarse <- do.call(rbind, rasters)
I'm not too familiar with .grd files, but this overall process should at least get you going in the right direction. Assuming all your .grd files (1 through 259) are stored in the same folder (which I will refer to as GRDFolder), then you can try this:
merge.coarse <- raster("coarseBlock1.grd")
for(filename in list.files(GRDFolder))
{
temp <- raster(filename)
merge.coarse <- rbind(merge.coarse, temp)
}