它是从顶部还是底部填充 [英] Does it fill from the top or bottom

查看:82
本文介绍了它是从顶部还是底部填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此MatLab代码转换为R.

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);

这是我所拥有的关于fillMissingData函数的信息:

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

要执行该功能的对象是位置" 2列矩阵,其数据如下所示:

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

我的解决方案只是使用r代码:

My solutions is just to use the r code:

positions <- na.locf(positions, fromLast=FALSE) 

填充以前的值,但是我不确定MatLab函数是否这样做,尤其是因为我被告知要携带0向前"

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"

请帮助!

推荐答案

将天真/单词到单词的R转换是

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
}

它的作用与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

这篇关于它是从顶部还是底部填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆