BWRT BWRT - 2 months ago 9x
R Question

R automatically use data table name in output

I have a function

which performs a bunch of things to a data.table and returns a raster dataframe. The function produces a raster that looks like this:

x y stdev
1: 265000 115000 0.0052252898
2: 265000 120000 0.0056821885
3: 265000 125000 0.0061935507
4: 265000 130000 0.0030856130
5: 265000 135000 0.0014861187
6: 265000 140000 0.0003941559

Presently I'm having to write the function output to a new data frame and save manually as a raster file:

wh.ras <- crop.raster(Wheat)
writeRaster(wh.ras, 'Wheat_unc.tif', overwrite=T)

This works but I have more data.tables to do this to. Is there a way that I can pull the data.table name that I feed into my function (e.g. Wheat) automatically into the output file name so that they all read
? I tried altering this and put it at the end of the function:

for (i in 1:length(rasnames)){
filenm <- rasnames[i]
writeRaster(rasterDF,c(filenm,"_unc",".tif"), overwrite=T)}

was a list of the names of the data tables (
rasnames = list("Wheat","Sbarley","Potato","OSR","fMaize")
). But i got this error:

Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘writeRaster’ for signature ‘"RasterLayer", "list"’


After following the advice below I changed
and whilst that now produces rasters it results in 5 copies of the same one with each having a name from the list. When I use the function (e.g.
) I only want the datatable entered as
to be in the filename.


If I understand your question correct you want to use the name of an object as a part of a file name. You can use deparse(substitute(obj)):

    ftest <- function(df) {
paste0(deparse(substitute(df)), ".tif")


# Output:
# [1] "iris.tif"

See: How to convert variable (object) name into String

If you want to use a list of strings as names you have to extract them with rasnames[[i]]. rasnames[i] returns a list. rasname[[i]] returns a text string.

ftest2 <- function(lst) {
  for (i in 1:length(lst)) {
    filename <- lst[[i]]
    filename <- paste0(filename, ".tif")
rasnames = list("Wheat","Sbarley","Potato","OSR","fMaize")

# Output:
# [1] "Wheat.tif"
# [1] "Sbarley.tif"
# [1] "Potato.tif"
# [1] "OSR.tif"
# [1] "fMaize.tif"