问题
I am trying to translate this MatLab code into R.
% ensure existing positions are carried forward
unless there is an exit signal positions=
fillMissingData(positions);
Here is the information I have about the fillMissingData function:
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
The object the function is performed on is "positions" a 2 column matrix with data that looks like this:
1 -1
1 -1
NaN NaN
NaN NaN
0 0
NaN NaN
1 -1
My solutions is just to use the r code:
positions <- na.locf(positions, fromLast=FALSE)
to fill with the previous value, but I am not sure if that is what the MatLab functions does, especially because I am told to "carry 0's forward"
Please help!
回答1:
A naive/word-to-word translation to R would be
fillMissingData <- function(prices){
filledPrices=prices
for (t in 2:nrow(filledPrices)){
missData=is.na(filledPrices[t, ])
filledPrices[t, missData]=filledPrices[t-1, missData]
}
filledPrices
}
And it does exactly what na.locf(positions, fromLast=FALSE)
does.
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
来源:https://stackoverflow.com/questions/27950664/does-it-fill-from-the-top-or-bottom