Does it fill from the top or bottom

江枫思渺然 提交于 2019-12-25 14:48:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!