arrays - 如何将数组缩放到另一个长度,保存 R 中的近似值

标签 arrays r resize scale rescale

我有两个不同长度的数组

value <- c(1,1,1,4,4,4,1,1,1)
time <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

如何调整 value 数组的大小,使其与 time 数组的长度相同,并保存其近似值?

approx() 函数表明长度不同。

我想让value数组像

value <- c(1,1,1,1,1,4,4,4,4,4,4,1,1,1,1)
time <-  c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)

所以长度相等

UPD

好的,主要目标是计算 v1 与 v2 的相关性,其中 v1 位于 data.frame v1,t1 内,v2 位于 data.frame v2,t2 内。

v1,t1 和 v2,t2 数据帧的长度不同,但是我们知道 t1 和 t2 的时间段相同,因此我们可以将它们重叠。

对于 t1,我们有 1,3,5,7,9,对于 t2,我们有 1,2,3,4,5,6,7,8,9,10。

问题是两个数据帧是分开但同时记录的,所以我需要缩放其中一个数据帧以覆盖另一个数据帧。然后我可以计算 v1 如何影响 v2 的相关性。

这就是为什么我需要将 v1 缩放到 t2 长度。

对不起,大家,我不知道如何正确地用英语写出目标。

最佳答案

您可以在approx中使用xout参数
xout:一组可选的数值,指定在何处进行插值。”。

# create some fake data, which I _think_ may resemble the data you described in edit.
set.seed(123)
# "for t1 we have 1,3,5,7,9"
df1 <- data.frame(time = c(1, 3, 5, 7, 9), value = sample(1:10, 5))
df1                  

# "for t2 we have 1,2,3,4,5,6,7,8,9,10", the 'full time series'.
df2 <- data.frame(time = 1:10, value = sample(1:10))

# interpolate using approx and the xout argument
# The time values for 'full time series', df2$time, is used as `xout`.
# default values of arguments (e.g. linear interpolation, no extrapolation)
interpol1 <- with(df1, approx(x = time, y = value, xout = df2$time))

# some arguments you may wish to check
# extrapolation rules
interpol2 <- with(df1, approx(x = time, y = value, xout = df2$time,
                              rule = 2))

# interpolation method ('last observation carried forward")
interpol3 <- with(df1, approx(x = time, y = value, xout = df2$time,
                              rule = 2, method = "constant"))

df1
#   time value
# 1    1     3
# 2    3     8
# 3    5     4
# 4    7     7
# 5    9     6

interpol1
# $x
# [1]  1  2  3  4  5  6  7  8  9 10
# 
# $y
# [1] 3.0 5.5 8.0 6.0 4.0 5.5 7.0 6.5 6.0  NA

interpol3
# $x
# [1]  1  2  3  4  5  6  7  8  9 10
# 
# $y
# [1] 3 3 8 8 4 4 7 7 6 6

# correlation between a vector of inter-(extra-)polated values
# and the 'full' time series
cor.test(interpol3$y, df2$value)

关于arrays - 如何将数组缩放到另一个长度,保存 R 中的近似值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21750806/

相关文章:

PHP/MySQL 更新顺序

R:在 3d 中绘制三角形的边

r - 如何使用 R 从 Yahoo Finance 抓取财务数据

html - 无需裁剪的响应图像

java - 如何在调整自定义 JSlider 大小时重新绘制

java - 使用 jSTL 迭代多维数组

用于获取对象值的有序数组的 Javascript (lodash) 函数

javascript - javascript 中的 Django 模板值

r - 将分组数据框导出到 excel 并为每个组创建一个单独的选项卡(R,dplyr)

android - 在 onDoubleTapEvent 上调整 imageview 的大小