首页 > 解决方案 > 在 r 中删除它们后如何保留索引/值

问题描述

删除它们后是否可以保留值及其索引?我的意思是我对测试一些插值方法很感兴趣,我想删除一些值,运行我的插值并将创建的新值与我之前删除的值进行比较。所以我随机删除一些值没有问题,但我不知道如何继续保留它们。我希望我的问题很清楚,

此致,

马克西姆

标签: r

解决方案


我认为这个问题的最佳答案是挑战其前提:您不必删除插值来进行另一种形式的插值。一个例子:

xvals <- 1:10 # These are the observed x values
yvals <- sin(xvals) # The observed y values
linear_interpolation <- approx(xvals, yvals) # linear interpolation of values
spline_interpolation <- spline(xvals, yvals, n = 50) # spline interpolation
# We can collect the interpolation results in a dataframe for easy comparison
comparison <- data.frame(x = linear_interpolation$x,
                         linear_interpolation = linear_interpolation$y,
                         spline_interpolation = spline_interpolation$y)
head(comparison) # Look at the first few rows
#>          x linear_interpolation spline_interpolation
#> 1 1.000000            0.8414710            0.8414710
#> 2 1.183673            0.8539289            0.9476460
#> 3 1.367347            0.8663868            1.0066238
#> 4 1.551020            0.8788447            1.0227805
#> 5 1.734694            0.8913027            1.0004924
#> 6 1.918367            0.9037606            0.9441358
# We can also plot them to compare visually
# I like to use the colorblind-friendly palette from
# Wong, Bang. 2011. "Points of view: Color blindness." Nature Methods 8:441.
wong_palette <- c("#e69f00", "#56b4e9", "#009e73")
# Start with the observed values
plot(xvals, yvals, pch = 19, xlab = "X Values", ylab = "Y Values",
     main = "Interpolation Comparison")
# Plot the linear interpolation
lines(linear_interpolation, col = wong_palette[1])
# The spline interpolation
lines(spline_interpolation, col = wong_palette[2])
# And, since we know the true function in this simulation, the true function
lines(linear_interpolation$x, sin(linear_interpolation$x), col = wong_palette[3])
# Finish with a legend so we know what we're looking at
legend("bottomleft", seg.len = 1, lty = 1, bty = "n", col = wong_palette,
       legend = c("Linear Interp.", "Spline Interp.", "True Function"))

reprex 包(v0.2.1)于 2018 年 11 月 18 日创建


推荐阅读