'Convert a dataframe into a matrix for 3d plotting in R

I am trying to plot a 3D volcano graph in R using plotly or any other package for that matter. The issue is the packages require a matrix to plot. I am having a difficult time converting the data frame into the desired matrix for plotting

Below is what I have already tried.

library(plotly)
library(reshape2)

df = structure(list(Net.Trading.PL = c(-427, -1372, -858, -293, -500, 
-161, -648, -1297, 378, -942, -730, -1699, -1586, -1546, 291, 
-941, -2229, -1256, -1596, -1175, 610, -1100, -1318, -1887, -2066, 
-1938, -1246, -1645, -1715, -1655, -2317, -2046, -1936, -1725, 
-1717, -2045, -929, -789, -977, -1157), nFAST = c(1L, 2L, 2L, 
3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 
6L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 
10L, 11L, 11L, 11L, 11L), nSLOW = c(42L, 50L, 72L, 33L, 60L, 
40L, 57L, 74L, 31L, 44L, 46L, 52L, 73L, 75L, 37L, 43L, 50L, 65L, 
66L, 69L, 30L, 41L, 46L, 58L, 78L, 46L, 56L, 72L, 75L, 76L, 47L, 
51L, 52L, 78L, 45L, 64L, 30L, 31L, 36L, 39L)), row.names = c(241L, 
402L, 842L, 63L, 603L, 204L, 544L, 884L, 25L, 285L, 325L, 445L, 
865L, 905L, 146L, 266L, 406L, 706L, 726L, 786L, 7L, 227L, 327L, 
567L, 967L, 328L, 528L, 848L, 908L, 928L, 349L, 429L, 449L, 969L, 
310L, 690L, 11L, 31L, 131L, 191L), class = "data.frame")

head(df)
    Net.Trading.PL nFAST nSLOW
           -427     1    42
          -1372     2    50
           -858     2    72
           -293     3    33
           -500     3    60
           -161     4    40

plot_matrix <- t(acast(df, nSLOW~nFAST, value.var="Net.Trading.PL"))
plot_matrix

However this does not give me the desired matrix for plotting.

I am trying to get the data into the right position so I can plot a graph like the one below where the x and z axis are nFAST and nSLOW and the Y axis in Trading Pnl. enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source