Home > Back-end >  R Getting numeric matrix from predict()
R Getting numeric matrix from predict()

Time:10-05

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.

CodePudding user response:

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()
  •  Tags:  
  • r
  • Related