您正在寻找outer
:
x <- 1:3
y <- 2:4
cbind(0, rbind(0, outer(x, y)))
# [,1] [,2] [,3] [,4]
# [1,] 0 0 0 0
# [2,] 0 2 3 4
# [3,] 0 4 6 8
# [4,] 0 6 9 12
Run Code Online (Sandbox Code Playgroud)
如果你想绘制z
每一对x
和y
值,你可能会发现使用它更方便
to.plot <- expand.grid(x=c(0, x), y=c(0, y))
to.plot$z = to.plot$x * to.plot$y
to.plot
# x y z
# 1 0 0 0
# 2 1 0 0
# 3 2 0 0
# 4 3 0 0
# 5 0 2 0
# 6 1 2 2
# 7 2 2 4
# 8 3 2 6
# 9 0 3 0
# 10 1 3 3
# 11 2 3 6
# 12 3 3 9
# 13 0 4 0
# 14 1 4 4
# 15 2 4 8
# 16 3 4 12
Run Code Online (Sandbox Code Playgroud)
然后你可以用以下东西绘图:
library(scatterplot3d)
scatterplot3d(to.plot$x, to.plot$y, to.plot$z)
Run Code Online (Sandbox Code Playgroud)