我正在尝试将此MatLab代码翻译为R。
% ensure existing positions are carried forward
unless there is an exit signal positions=
fillMissingData(positions);
以下是有关fillMissingData函数的信息:
function [filledPrices]=fillMissingData(prices)
% [filledPrices]=fillMissingData(prices) fill data in a 2-dim array with NaN's with the
% previous value.
filledPrices=prices;
for t=2:size(filledPrices, 1)
missData=~isfinite(filledPrices(t, :));
filledPrices(t, missData)=filledPrices(t-1, missData);
end
执行该功能的对象是"位置"一个2列矩阵,其数据如下所示:
1 -1
1 -1
NaN NaN
NaN NaN
0 0
NaN NaN
1 -1
我的解决方案就是使用r代码:
positions <- na.locf(positions, fromLast=FALSE)
填写之前的值,但我不确定这是否是MatLab函数的作用,特别是因为我被告知&#34;进行0&#39; s&#34;
请帮忙!
答案 0 :(得分:3)
对R的简单/单词到单词的翻译将是
fillMissingData <- function(prices){
filledPrices=prices
for (t in 2:nrow(filledPrices)){
missData=is.na(filledPrices[t, ])
filledPrices[t, missData]=filledPrices[t-1, missData]
}
filledPrices
}
它完全符合na.locf(positions, fromLast=FALSE)
的作用。
positions <- matrix(c(1, -1, 1, -1, NA, NA,NA, NA,0, 0,NA, NA, 1, -1), ncol=2, byrow=TRUE)
fillMissingData(positions)
# [,1] [,2]
#[1,] 1 -1
#[2,] 1 -1
#[3,] 1 -1
#[4,] 1 -1
#[5,] 0 0
#[6,] 0 0
#[7,] 1 -1