1
votes

Is there anyway to view the hexbins as a data.frame?

dat = data.frame(x = rnorm(10000), y = rnorm(10000))
hbin <- hexbin::hexbin(dat$x, dat$y, xbins = 40)
as.data.frame(hbin)

Error in as.data.frame.default(hbin) : cannot coerce class ‘structure("hexbin", package = "hexbin")’ to a data.frame

1

1 Answers

0
votes

hexbin objects are S4 data (here is a great resource about manipulating S4 in R by Hadley Wickham), so if you see:

require(hexbin)
dat <- data.frame(x = rnorm(10000), y = rnorm(10000))
hbin <- hexbin::hexbin(dat$x, dat$y, xbins = 40)
str(hbin)

#> Formal class 'hexbin' [package "hexbin"] with 16 slots
#>   ..@ cell  : int [1:1003] 19 96 110 133 148 149 179 180 181 182 ...
#>   ..@ count : int [1:1003] 1 1 1 1 1 1 1 1 1 1 ...
#>   ..@ xcm   : num [1:1003] -0.335 -1.267 1.246 -1.771 0.841 ...
#>   ..@ ycm   : num [1:1003] -3.75 -3.49 -3.39 -3.28 -3.28 ...
#>   ..@ xbins : num 40
#>   ..@ shape : num 1
#>   ..@ xbnds : num [1:2] -3.55 3.69
#>   ..@ ybnds : num [1:2] -3.75 3.28
#>   ..@ dimen : num [1:2] 48 41
#>   ..@ n     : int 10000
#>   ..@ ncells: int 1003
#>   ..@ call  : language hexbin::hexbin(x = dat$x, y = dat$y, xbins = 40)
#>   ..@ xlab  : chr "dat$x"
#>   ..@ ylab  : chr "dat$y"
#>   ..@ cID   : NULL
#>   ..@ cAtt  : int(0)

Then, you can subset parts of hbin with the @ operation. For example, if you wanted to include hbin.xcm and hbin.ycm in a data frame (both vectors with 10003 elements long).

df <- data.frame(xcm = hbin@xcm, ycm = hbin@ycm) 
head(df)

#>           xcm       ycm
#> 1 -1.15641677 -3.464301
#> 2 -0.67133436 -3.435775
#> 3  0.08136055 -3.422812
#> 4  0.80232574 -3.437158
#> 5 -3.06306998 -3.314999
#> 6 -1.39092669 -3.101475