Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试绘制曲面时for循环出错_R_R Plotly - Fatal编程技术网

尝试绘制曲面时for循环出错

尝试绘制曲面时for循环出错,r,r-plotly,R,R Plotly,我试图在R中绘制一个3d曲面,但当X和Y的值都为正值时,for循环中似乎出现了问题 这是一个非常简单的函数和for循环,但我还没有看到错误,仍然是最终的曲面不同于它应该是什么(在这种情况下是一个法线平面)。有没有想过我会错过什么 library(ggplot2) library(plotly) x = seq(-5,5) y = seq(-5,5) fxy = matrix(0,length(y),length(x)) dim(fxy) result = function(x,y){

我试图在R中绘制一个3d曲面,但当X和Y的值都为正值时,for循环中似乎出现了问题

这是一个非常简单的函数和for循环,但我还没有看到错误,仍然是最终的曲面不同于它应该是什么(在这种情况下是一个法线平面)。有没有想过我会错过什么

library(ggplot2)
library(plotly)    

x = seq(-5,5)
y = seq(-5,5)
fxy = matrix(0,length(y),length(x))
dim(fxy)

result = function(x,y){
  x+y
  }

for (j in y) {
  for (i in x) {
    fxy[i,j] = result(x[i],y[j])
  }
}

fig = plot_ly(z = ~fxy, x = x, y=y)
fig = fig %>% add_surface()

fig


谢谢你的帮助

您的循环应该使用
沿(x)
沿(y)
而不是
x
y

library(ggplot2)
library(plotly)    

x = seq(-5,5)
y = seq(-5,5)
fxy = matrix(0,length(y),length(x))
dim(fxy)

result = function(x,y){
    x+y
}

for (j in seq_along(y)) {
    for (i in seq_along(x)) {
        fxy[i,j] = result(x[i],y[j])
    }
}

fig = plot_ly(z = ~fxy, x = x, y=y)
fig = fig %>% add_surface()

fig

谢谢你的回答,用户12728748。我想我是把整个向量传递给函数,而不是每个元素本身。seq_along()解决了这个问题!不完全是这样;您试图在
fxy[i,j]=result(x[i],y[j]
行中处理x和/或y为负的负索引。请尝试以下玩具示例:
fxy=matrix(seq(1,(length(y)*length(x)),length(y),length(x));fxy[1,1];fxy[-1,1]
,看看接下来会发生什么。。。