Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Getting numeric matrix from predict()

Tags:

r

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.

like image 882
Thomas Severin Avatar asked Sep 15 '26 13:09

Thomas Severin


1 Answers

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()
like image 166
AndS. Avatar answered Sep 17 '26 01:09

AndS.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!