G1124E G1124E - 3 months ago 21
R Question

Finding values by linear interpolation in r

I have huge data that I need to find the values of several variables at a standard height.
I want to interpolate linearly the values of the other variables at

Height=c(0,100,200,250,400,500)
and add them as new columns to the existing data. Here is what I tried to get a value for one variable as the standard
Height=c(0,100,200,250,400,500)
. This is just for one variable:

data2<-approx(data2$Height,data2$ozone,xout=c(0,100,200,250,400,500))


The expected result should be a data frame with 18 rows and 4 columns.

Here is sample data
(data2)
:

ozone Height Temp Wind
23.224833 0.000000 253.005798 3.631531
23.750044 35.218689 253.299332 5.178889
24.589071 70.661133 253.538574 6.892455
25.619747 106.267334 253.492661 8.050934
26.443541 142.014648 253.279053 8.648781
27.235945 213.897034 252.815262 9.263882
27.698713 286.280518 252.10556 9.269853
27.865248 359.172363 251.390045 9.3006
28.361752 432.788086 251.379913 8.90488
30.279163 507.276733 251.849655 7.817647
23.048151 0.000000 251.528275 4.174027
23.477306 34.998413 251.6698 5.630364
24.16725 70.187622 251.759369 7.237537
25.239206 105.544006 251.744934 8.859097
26.319073 141.05011 251.601654 9.928196
27.409718 212.47052 251.214279 10.75243
27.825275 284.45282 250.738007 10.812123
28.214966 357.184631 250.87706 9.980968
29.726873 430.919983 251.84964 9.139032
32.482925 505.574097 252.471924 8.063484
22.369734 0.000000 250.876144 3.82036
22.916582 34.908447 251.044205 5.281044
23.732521 70.014038 251.170456 6.970277
24.998178 105.296021 251.221603 8.801399
26.30809 140.736084 251.133591 10.039667
27.572966 212.052795 250.852631 11.118568
28.233795 283.998474 250.61908 10.677624
29.079391 356.812012 251.179962 9.466641
31.244007 430.597534 252.042175 9.016301
33.636559 505.305542 252.659393 8.103294


Thank you in advance for your help.

Answer

You just work through columns using lapply. Plus, you can't append your interpolated values to your data2. data2 has 30 rows, while xout has length 6. You need another data frame to hold interpolation result.

height_out <- 0:5 * 100
cbind.data.frame(data.frame(Height = height_out),
                 lapply(data2[-2], function (u) approx(data2[[2]], u, height_out)$y))

#  Height    ozone     Temp      Wind
#1      0 22.88091 251.8034  3.875306
#2    100 24.93562 251.5759  8.509502
#3    200 27.37860 251.2702 10.693545
#4    300 27.96728 251.9255  9.308131
#5    400 29.79659 251.7628  9.138091
#6    500 33.25064 252.5658  8.161940