简体   繁体   English

列的 R 中的线性插值

[英]Linear interpolation in R for columns

I have a table with column called 'rates'.我有一个名为“费率”列的表格。 This column include missing values.此列包括缺失值。 I need to calculate linear function where missing values are calculated based on previous existing value and a value that follows the missing value, and there should be an equal interval between replaced missing values.我需要计算线性函数,其中缺失值是根据先前的现有值和缺失值之后的值计算的,并且替换的缺失值之间应该有相等的间隔。

For example, column 'rates' include values: 0,66 Na Na Na 0,77 0,75 0,79 Na Na 0,79例如,列 'rates' 包括值: 0,66 Na Na Na 0,77 0,75 0,79 Na Na 0,79

And I need to get a new column where Na values will be replaced in R the way I described above.而且我需要得到一个新列,其中 Na 值将按照我上面描述的方式在 R 中替换。

You could use na.approx from the zoo package.您可以使用zoo包中的na.approx The function according to document:根据文档的功能:

Generic functions for replacing each NA with interpolated values.用插值替换每个 NA 的通用函数。

Code:代码:

df <- data.frame(rates = c(0.66, NA, NA, NA, 0.77, 0.75, 0.79, NA, NA, 0.79))

library(zoo)
df$new_rates <- na.approx(df$rates)
df
#>    rates new_rates
#> 1   0.66    0.6600
#> 2     NA    0.6875
#> 3     NA    0.7150
#> 4     NA    0.7425
#> 5   0.77    0.7700
#> 6   0.75    0.7500
#> 7   0.79    0.7900
#> 8     NA    0.7900
#> 9     NA    0.7900
#> 10  0.79    0.7900

Created on 2022-07-05 by the reprex package (v2.0.1)reprex 包于 2022-07-05 创建 (v2.0.1)

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

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