2016-04-25 90 views
1

我有两个载体:创建从一个矢量的功能到另一个

x <- c(-2.0,-1.75,-1.50,-1.25,-1.00,-0.75,-0.50,-0.25,0.00,0.25,0.50,0.75,1.00,1.25,1.50,1.75,2.00,2.25,2.50,2.75) 
y <- c(37.0000,24.1602,15.06250,8.91016,5.00000,2.72266,1.56250,1.09766,1.00000,1.03516,1.06250,1.03516,1.00000,1.09766,1.56250,2.72266,5.00000,8.91016,15.06250,24.16016) 

我试图创建一个给定的从向量x的数的函数,则返回对应的y值(相同的索引)。例如,func(-2.0)应返回37.0000

目前我有这个超级难看的函数,我不认为什么是我应该做的事:

func1 <- function(x) { 
    if (x==-2.0) {return (37.0000)} 
    else if (x==-1.75){return (24.1602)} 
    else if (x==-1.50){return (15.06250)} 
    else if (x==-1.25){return (8.91016)} 
    else if (x==-1.00){return (5.00000)} 
    else if (x==-0.75){return (2.72266)} 
    else if (x==-0.50){return (1.56250)} 
    else if (x==-0.25){return (1.09766)} 
    else if (x==0.00){return (1.00000)} 
    else if (x==0.25){return (1.03516)} 
    else if (x==0.50){return (1.06250)} 
    else if (x==0.75){return (1.03516)} 
    else if (x==1.00){return (1.00000)} 
    else if (x==1.25){return (1.09766)} 
    else if (x==1.50){return (1.56250)} 
    else if (x==1.75){return (2.72266)} 
    else if (x==2.00){return (5.00000)} 
    else if (x==2.25){return (8.91016)} 
    else if (x==2.50){return (15.06250)} 
    else if (x==2.75){return (24.16016)} 
    else {return (Inf)} 
} 
+3

无需功能,'Y [其中(X == -2.0)]'。 – zx8754

回答

2

精确匹配:

foo = function(u) {res=y[pmatch(u,x)];ifelse(is.na(res), Inf, res)} 
#> foo(-2) 
#[1] 37 
#> foo(-1.8) 
#[1] Inf 
#> foo(-4) 
#[1] Inf 

你需要什么不知道,但请注意,您可以使用线性插值(可以将方法视为常数而不是线性):

foo = approxfun(x,y, yleft=Inf, yright=Inf) 
#> foo(-2) 
#[1] 37 
#> foo(-1.8) 
#[1] 26.72816 
#> foo(-4) 
#[1] Inf 

In这最后一种情况下,该值不是由x定义的边界域中的Inf。

+0

添加选项来处理'else {return(Inf)}' – zx8754

0

由于x和y的长度相同,把X为y的名字

names(y)<-x 
y 

     -2 -1.75  -1.5 -1.25  -1 -0.75  -0.5 -0.25  0  0.25  0.5  0.75  1  1.25  1.5  1.75  2 
37.00000 24.16020 15.06250 8.91016 5.00000 2.72266 1.56250 1.09766 1.00000 1.03516 1.06250 1.03516 1.00000 1.09766 1.56250 2.72266 5.00000 
    2.25  2.5  2.75 
8.91016 15.06250 24.16016 

这样,您就可以通过名字,例如呼叫

y["-2"] 

-2 
37 

y["-1.75"] 

-1.75 
24.1602 
+0

考虑到这一点,'myInput < - -2; y [as.character(myInput)]'... – zx8754

0

你并不真的需要这个功能,我建议你只需使用:

y[x == -1.75] 

X == -1.75返回一个布尔值向量,因此会选择Y的正确的价值。

如果你真的想要一个功能:

f <- function(x,y,xi){ 
return(y[x == xi]) 
} 
+0

'哪()'更有效率。 – zx8754

2

你似乎在做插值。用于插值的R函数是approx()

approx(x, y, xout = -2) 

$x 
[1] -2 

$y 
[1] 37 

实际上,使用approxfun()可以更容易地创建插值函数。试试这个:

foo <- approxfun(x, y) 
foo(-2) 
[1] 37 

你或许应该避免使用使用==match()精确匹配的策略。原因很简单 - 如果您使用计算值来查找索引位置,则可能发现匹配不准确。

比较:

y[ which(x == -2.0) ] 
[1] 37 

y[ which(x == -2.00000000001) ] 
numeric(0) 

类似地:

y[match(-2.0, x)] 
[1] 37 

y[match(-2.0000000000001, x)] 
[1] NA 
+1

approxfun是我的建议分钟前...它需要yright和yleft选项而且处理OP要求...而且这只是一种'替代解决方案',也许OP希望在'x'的'洞'中真正使用Inf。 –