If you convert the raster to a data frame with xy=TRUE
you get a data frame with the coordinates and the altitude:
> ed = as.data.frame(elevation,xy=TRUE)
> head(ed)
x y BGD_msk_alt
1 87.90417 26.69583 NA
2 87.91250 26.69583 NA
3 87.92083 26.69583 NA
4 87.92917 26.69583 NA
5 87.93750 26.69583 NA
6 87.94583 26.69583 NA
The NA values are because you have a rectangular grid which is masked to the country boundary - anything outside the boundary is given NA. If you don't want those, remove them by subsetting rows on the third column:
> ed2 = ed[!is.na(ed[,3]),]
> head(ed2)
x y BGD_msk_alt
4766 88.41250 26.62917 105
5353 88.40417 26.62083 105
5354 88.41250 26.62083 103
5940 88.39583 26.61250 103
5941 88.40417 26.61250 102
5942 88.41250 26.61250 101
You can then use standard R functions (eg write.table
) to produce a CSV, which is well documented elsewhere.