r - Create a function from a vector to another -


i have 2 vectors:

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) 

i trying create function given number vector x, returns corresponding y value(same index). example, func(-2.0) should return 37.0000.

currently have super ugly function don't think supposed do:

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)} } 

for exact matching:

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 

not sure need beware can use linear interpolation (you can put method constant instead of linear):

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

in last case, value not inf in boundary domain defined x.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -