adj output to show the cell directions

12 views
Skip to first unread message

0he...@gmail.com

unread,
Jun 23, 2020, 2:27:58 AM6/23/20
to SpaDES Users
Hi there,

I am trying to obtain the cell directions of the 8 nearest neighbors, That is I want to know the cell values for each neighbor of each cell similar to this https://stackoverflow.com/questions/56771620/get-values-from-adjacent-cells-raster-r?rq=1. The current implementation of this is very slow, about 16 times slower then using SpaDDES::adj. However, I am unable to obtain the cell directions from this?
Any suggestions?
Thanks Herry
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
reproducible example:
 require(raster)
 require(dplyr)
 set.seed(666)
 r <- raster(matrix(sample.int(10000), 100))
a<-SpaDES.tools::adj(numCol=ncol(r),numCell=ncell(r),cells=1:ncell(r),
                     directions=8, include=T, pairs=T, sort=F, returnDT=T,
                     numNeighs=8)

# assign values to cell numbers
cells<-1:ncell(r)
vals<-r[]

a1=as.data.frame(a)%>%arrange(from)%>%
  mutate(count=tabulate(unique(a)$from)[a$from])
counter=a1%>%group_by(from)%>%tally()%>%select(n)%>%
  unlist%>%sapply(.,function(x)1:x)%>%unlist
a2=a1%>%mutate(counter=counter)
a3=dplyr::bind_cols(a2,
                 toVals=plyr::mapvalues(unlist(a[,2]),from=cells,to=vals))%>%
  arrange(from)
a4=data.table::dcast(data.table::setDT(a3), from ~ counter,  value.var = "toVals")
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Eliot McIntire

unread,
Jun 23, 2020, 12:21:55 PM6/23/20
to spades...@googlegroups.com
If you just want angles, use the base::atan2 on the x,y version of the pixel numbers:


require(raster)
require(dplyr)
set.seed(666)
r <- raster(matrix(sample.int(10000), 100))
a<-SpaDES.tools::adj(numCol=ncol(r),numCell=ncell(r),cells=1:ncell(r),
                     directions=8, include=T, pairs=T, sort=F, returnDT=T,
                     numNeighs=8)
v2 <- raster::xyFromCell(r, a[,from])
v1 <- raster::xyFromCell(r, a[,to])
angleInRads <- atan2(v2[,"y"] - v1[,"y"], v2[,"x"] - v1[, "x"]) # https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors
(angleInDegs <- CircStats::deg(angleInRads))

You can also try to use SpaDES.tools::directionFromEachPoint which may do what you need

Alex Chubaty

unread,
Jun 23, 2020, 12:23:35 PM6/23/20
to SpaDES Users
You can get the values of the adjacent cells by doing:

a[, value := r[to]]

Alex
Reply all
Reply to author
Forward
0 new messages