Search code examples
rasciiarcgis

dataframe to ArcGIS ASCII in R


I have a data frame (predHB.Lv1Hard) that contains 3 columns "y" = Longitude, "x" = Latitude and "predLv1Hard" = probability of a model output. All columns are numeric.

> head(predHB.Lv1Hard)
      y        x      predLv1Hard
1 -21.78557 114.0319  0.00000000
2 -21.78557 114.0319  0.06315789
3 -21.78557 114.0320  0.00000000
4 -21.78557 114.0320  0.00000000
5 -21.78557 114.0321  0.00000000
6 -21.78557 114.0321  0.00000000

I am trying to work out how to now export this to an ASCII that I can open in ArcGIS (either in .txt or ideally, .asc format).

The code (SPlus) that I'm trying to emulate is shown below (there doesn't seem to be an equivalent export.data function in R.)

export.data(DataSet = "predHB.Lv1Hard", Columns ="ALL", Rows = "ALL", Delimiter = ",", ColumnNames = T, 
FileName="C:/working/predHBLv1Hard.txt" , FileType="ASCII")

Solution

  • Check the package raster.

    You first need convert the dataframe to a raster file (re-arrange the columns to match xyz):

    r <- rasterFromXYZ(predHB.Lv1Hard[,c(2,1,3)])
    

    and then use:

    writeRaster(r,'filename.asc', format='ascii')
    

    If the points are not in a regular grid, you can try the function rasterize. There is not much I can do with the head of that file but an example could be:

    # Convert to SpatialPoinDataFrane
    coordinates(predHB.Lv1Hard) <- ~x+y
    
    # Calculate the extent of the observations
    ext <- extent(predHB.Lv1Hard)
    
    # Get the distance between points
    table(diff(predHB.Lv1Hard@coords[,1]))
    #0 0.00010000000000332 
    #3                   2
    # With the limited info I have I could assume that the resolution is 0.00010000000000332 degrees.
    # If you know the original resolution, much better.
    
    # Create the template
    r <- raster(ext=ext,res=0.00010000000000332)
    # Final raster
    to_ascii <- rasterize(predHB.Lv1Hard, r, 'predLv1Hard')
    
    # Write raster to ascii
    writeRaster(to_ascii,'filename.asc', format='ascii')