Cannot export a raster image after using the random forest classification

There is a typo in your last line (overwrite-TRUE). It should read:

writeRaster("rf2", filename = "rf2.tif", format = "raster", overwrite = TRUE)

RStudio’s code diagnostics are a great help for catching this sort of thing!

Also, a tip: it is very difficult to read code that isn’t formatted as code (especially, since some of the special characters, like comments, get misinterpreted by the forum’s built-in Markdown engine). Here’s how to help your helpers and make the code in your posts more readable.