sigAND
当两个选定的列都具有值(或不是 NA)时,在创建具有日期的新列时很有用。感谢 Ilya Kipnis 和他的IKTrading
包裹。
但是,我注意到在这个函数的帮助页面中,cross
是使用的。我很困惑,如果我对sigAND
上面的用法的理解是正确的,那么应该没有cross
.
我查看了sigAND
源代码,并对其进行了测试。该函数可以正常工作,并且当cross = TRUE
输出列只是NA
or的向量时FALSE
。cross
因此,在函数中似乎没有真正的意义。
这是我的假数据和输入:
dataAnd <- cbind(c(1, NA, 3, NA, NA, 10, 12), 7:13)
dataAnd <- xts(dataAnd, order.by = Sys.Date()+1:7)
colnames(dataAnd) <- c("col1", "col2")
label = "both"
data = dataAnd
columns = c("col1", "col2")
cross = T # F
这是sigAND
带有一些注释的源代码,以帮助自己理解代码(我对 R 和编程仍然很陌生)。
function (label, data = mktdata, columns, cross = FALSE)
# cross = False is important, as cross=T makes no sense here.
# columns: named colums to apply comparison to
#{
# create an empty return_signal_column
ret_sig = NULL
colNums <- rep(0, length(columns)) # colNums <- c(0, 0)
for (i in 1:length(columns)) { # for each column
# example of how to use match.names()
# match.names("Close", colnames(IF_DAY)) return 4, index of '.Close'
# colNums[i] <- 4 assigned with an index
colNums[i] <- match.names(columns[i], colnames(data))
}
# extract the first/left column to be a one-column xts and assigned to ret_sig
ret_sig <- data[, colNums[1]]
# for second or third comparing column
for (i in 2:length(colNums)) {
# check whether a date has values in both columns, yes(true), no(NA)
# example: 1:4 & c(1, NA, NA, 10)
# return: [1] TRUE NA NA TRUE
ret_sig <- ret_sig & data[, colNums[i]]
}
# turn above [1] TRUE NA NA TRUE to [1] 1 NA NA 1
ret_sig <- ret_sig * 1
#### using cross option here makes no sense, right?
# if cross was assigned to be True
if (isTRUE(cross))
# create ret_sig logic value by diff(ret_sig) == 1
ret_sig <- diff(ret_sig) == 1 # !!!! NA-1 or 1-NA are NA
# name ret_sig to be label
colnames(ret_sig) <- label # label is given to the output
return(ret_sig)
}
我加载了数据和输入,并在没有注释掉的第一行和最后几行的情况下运行了上面的源代码。
我得到以下输出时cross = FALSE
:
> ret_sig
both
2016-03-19 1
2016-03-20 NA
2016-03-21 1
2016-03-22 NA
2016-03-23 NA
2016-03-24 1
2016-03-25 1
我得到以下输出时cross = TRUE
:
> ret_sig
both
2016-03-19 NA
2016-03-20 NA
2016-03-21 NA
2016-03-22 NA
2016-03-23 NA
2016-03-24 NA
2016-03-25 FALSE
第二种情况表明,在那里没有意义cross
。或者,我在这里遗漏了一些重要的东西吗?有人可以看看吗?