Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R Getting numeric matrix from predict()

I have the following code:

fit_lm=lm(z~x+y)

mix <- 2
max <- 12
miy <- 2
may <- 12

griddf <- expand.grid(x = seq(mix,max, length.out = 10),
                      y = seq( miy,may,length.out = 10))


Prediction_data <- data.frame(griddf)
colnames(Prediction_data) <- c("x", "y")
coordinates(Prediction_data ) <- ~ x + y

terrain_lm <- predict(fit_lm, Prediction_data)

I want that terrain_lm is a numeric matrix, in such a way, that I can use

fig <- plot_ly()

fig <- fig %>%  add_surface(terrain_lm)

but I get a 1d array with 100 elements.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The result of predict is a vector. You need to add it to the x and y values and then use xtabs to transform into a suitable matrix for a surface plot.

library(plotly)

#test data
x <- runif(20, 4, 10)
y <- runif(20, 3, 6)
z <- 3*x+y +runif(20, 0, 2)

fit_lm <- lm(z~x+y)


mix <- 2
max <- 12
miy <- 2
may <- 12

griddf <- expand.grid(x = seq(mix,max, length.out = 10),
                      y = seq( miy,may,length.out = 10))


terrain_lm <- data.frame(griddf)
terrain_lm$z <- predict(fit_lm, terrain_lm)

fig <- plot_ly(z = ~xtabs(z ~ x + y, data = terrain_lm))
fig <- fig %>%  add_surface()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading