1

I am learning interpolation using R. I found a code online and I am not sure about the function of $y at the end of the code. I tried to run the code with and without $y and I cannot really tell the differences.

test <- approx(x, y, xout=c, rule=2) $y
lovalery
  • 4,524
  • 3
  • 14
  • 28
Selena
  • 33
  • 3
  • `?approx` : approx returns a list with components x and y, containing n coordinates which interpolate the given data points according to the method (and rule) desired. – Waldi Feb 03 '22 at 17:06
  • Hi, Thanks for your reply!! How about the $y at the end of the interpolation function? – Selena Feb 03 '22 at 17:08
  • 1
    In R, you can access elements of a list using `$`, e.g. MY_LIST$ELEMENT_NAME. So if `approx` outputs a list with an element called `y`, adding `$y` at the end gives you that part of the list. In this case you want the vector `y`, not the other parts of the list that `approx` outputs. – Jon Spring Feb 03 '22 at 17:13

1 Answers1

2

$ is one way to access elements of a list in R.

(Some more explanation: https://stackoverflow.com/a/1169495/6851825 or https://stackoverflow.com/a/32819641/6851825)

This code will produce a list of x values (from the c term we provided) and interpolated y values.

x = 1:3
y = 4:6
c = seq(1,3,by = 0.5)
approx (x, y, xout=c, rule=2)

The output R gives us tells us that it's a list with components called x and y.

$x
[1] 1.0 1.5 2.0 2.5 3.0

$y
[1] 4.0 4.5 5.0 5.5 6.0

We could examine the structure of this output by running:

str(approx (x, y, xout=c, rule=2)) 

#List of 2
# $ x: num [1:5] 1 1.5 2 2.5 3
# $ y: num [1:5] 4 4.5 5 5.5 6

If we just want the y part, the interpolated values, we can run approx (x, y, xout=c, rule=2)$y to get it. Instead of a list, this is a numeric vector.

[1] 4.0 4.5 5.0 5.5 6.0
Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Thank you so much for your answer!! I thought "$y" is some sort of trek in R.. Did not think it as the regular way to access elements under interpolation function. Thankssssss!!!!! – Selena Feb 03 '22 at 18:18