我正在尝试创建一个循环,将平滑函数应用于我感兴趣的所有变量。我使用的数据集是R中的aemet数据集,重点是温度。为了在第10列上应用平滑,我运行了以下代码,运行良好。
library(fda)
library(fda.usc)
data(aemet,package = "fda.usc")
tt = aemet$temp$argvals
temp = as.data.frame(aemet$temp$data,row.names=F)
range.tt = aemet$temp$rangeval
inv.temp = data.frame(t(aemet$temp$data)) # 365 x 73 matrix
names(inv.temp) = aemet$df$name # Oviedo is the 10th column of inv.temp
ovibasis5 = create.fourier.basis(rangeval = range(tt),nbasis = 5)
ovifourier5.fd = smooth.basis(argvals = tt, y = inv.temp[,i],fdParobj = ovibasis5)$fd
ovi5 = eval.fd(tt,ovifourier5.fd)
ovi5
接下来,我想对数据集中的所有73列应用平滑,所以我使用了循环函数,如下所示
for(i in 1: inv.temp){
ovibasis5 = create.fourier.basis(rangeval = range(tt),nbasis = 5)
ovifourier5.fd = smooth.basis(argvals = tt, y = inv.temp[,i],fdParobj = ovibasis5)$fd
ovi5[,i] = eval.fd(tt,ovifourier5.fd)
}
ovi5
但是我得到这个错误信息1中的错误:inv。temp: NA/NaN参数警告信息:1:发票。数值表达式有73个元素:只使用第一个比;比;ovi5"
我做错了什么?
您可以将ovibasis5
置于循环之外,因为它是常量,并且在循环中不会改变它的值。初始化输出矩阵(ovi5
),其行数和列数与inv.temp
相同。
library(fda)
library(fda.usc)
ovibasis5 = create.fourier.basis(rangeval = range(tt),nbasis = 5)
ovi5 <- matrix(nrow = nrow(inv.temp), ncol = ncol(inv.temp))
for(i in seq_along(inv.temp)){
ovifourier5.fd = smooth.basis(argvals = tt, y = inv.temp[,i],fdParobj = ovibasis5)$fd
ovi5[,i] = eval.fd(tt,ovifourier5.fd)
}
#Sample output
ovi5[1:5, 1:5]
# [,1] [,2] [,3] [,4] [,5]
#[1,] 10.99621 9.378179 7.839638 4.930860 5.370917
#[2,] 10.97734 9.360540 7.827852 4.913171 5.365705
#[3,] 10.95973 9.344325 7.817700 4.897670 5.362975
#[4,] 10.94339 9.329520 7.809155 4.884335 5.362678
#[5,] 10.92829 9.316107 7.802192 4.873138 5.364765
#complete output
ovi5