简体   繁体   English

R中的多元概率密度函数

[英]Multivariate probability densitiy function in R

I want to create a multivariate probability density function with R to plot it as a perspective plot. 我想用R创建一个多元概率密度函数,将其绘制为透视图。 f(x,y) is x+y for [0,1]*[0,1], 0 else. 对于[0,1] * [0,1],f(x,y)是x + y,否则为0。 I tried this: 我尝试了这个:

x <- seq(-0.5,1.5,length=50)*seq(0.5,1.5,length=50)
y <- x

f <- function(x,y){
  if (0<=x<=1 && 0<=y<=1){
    x+y
  } else {
    0
  }
}
f(x,y)  

But the function is not working and I don't know how to fix it. 但是该功能无法正常工作,我不知道如何解决。 Does anyone have an idea? 有人有主意吗?

First of all your if statement is wrong. 首先,您的if语句是错误的。 This would fix the if statement but would still give the error. 这将修复if语句,但仍会给出错误。

x <- seq(-0.5,1.5,length=50)*seq(0.5,1.5,length=50)
y <- x

f <- function(x,y){
  if (0<=x & x<=1 & 0<=y & y<=1){
    x+y
  } else {
    0
  }
}

f(x,y) 

f1 <- function(x,y){
  cond <- 0<=x &x<=1 & 0<=y&y<=1
  ifelse(cond, x+y, 0)
}

f1(x,y)
[1] 0
Warning message:
In if (0 <= x & x <= 1 & 0 <= y & y <= 1) { :
  the condition has length > 1 and only the first element will be used

You need to vectorize your function in order to give it vector arguments. 您需要对函数进行向量化,以便为其提供向量参数。 One way is to use function ifelse which is vectorized version of if and else 一种方法是使用ifelse函数,它是ifelse向量化版本

f1 <- function(x,y){
  cond <- 0<=x & x<=1 & 0<=y & y<=1
  ifelse(cond, x+y, 0)
}

f1(x,y)
 [1] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
 [9] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.04685548 0.11224490 0.18096626
[17] 0.25301958 0.32840483 0.40712203 0.48917118 0.57455227 0.66326531 0.75531029 0.85068721
[25] 0.94939608 1.05143690 1.15680966 1.26551437 1.37755102 1.49291962 1.61162016 1.73365264
[33] 1.85901708 1.98771345 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[41] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[49] 0.00000000 0.00000000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM