带有 ifelse 的自定义函数和两个对象需要以动态方式从正确的列中读取 R

custom function with ifelse and two objects needs to read from correct column in a dynamic way R

如何确定对象中两列的数据(数据) 通过自定义函数以动态方式查看另一个对象 (B_u) 的相应列?

参见下面的示例:

# example data
require(xts)
set.seed(3)    
A    <- matrix(runif(18, max=9), ncol=2)
Data <- xts(A, Sys.Date()-9:1)
names(Data) <- c("C1", "C2")

这会生成:

                 C1       C2
2016-04-28 1.512374 5.678813
2016-04-29 7.267648 4.608143
2016-04-30 3.464481 4.545215
2016-05-01 2.949609 4.806318
2016-05-02 5.418906 5.015245
2016-05-03 5.439546 7.811275
2016-05-04 1.121701 7.467378
2016-05-05 2.651408 1.003042
2016-05-06 5.198489 6.333195

我对这些数据进行分位数(底部 20% 和顶部 20%):

# make quantiles based on dataset
B_q  <- (apply(t(Data), 1, FUN=quantile, probs=c(0.2,0.8), na.rm=TRUE))
B_l  <- B_q[1,]
B_u  <- B_q[2,]

这导致:

对于B_l

  C1       C2
2.195794 4.582972 

和B_u

      C1       C2 
5.427162 6.786868

创建函数:

# function to test whether data is bigger than the quantile
test_a <- function(x,l,u)
{
   for (i in 1:(nrow(x)))
   for (j in 1:(ncol(x)))

    b <- ifelse(x > u[j] , 1, 0)

  return(b)
}

调用函数时问题/问题从这里开始

# calling the function (dynamic)
# How can i make sure the data of both columns in Data
# look in the corresponding columns of B_u?

result_wrong <- test_a(Data, B_l, B_u)

结果:

           C1 C2
2016-04-28  0  0
2016-04-29  1  0
2016-04-30  0  0
2016-05-01  0  0
2016-05-02  0  0
2016-05-03  0  1
2016-05-04  0  1
2016-05-05  0  0
2016-05-06  0  0

其中 2016-05-03 的 C1 给出了错误的结果,因为它应该是一个。当我显式调用该列时,可以从下一个结果中看到这一点

# calling the function with explicit columns)
# If I explicit the column to look into, it works. 
# However I have 100 columns of data so that won't work

result_correct <- test_a(Data[,1], B_l[1], B_u[1])

           C1
2016-04-28  0
2016-04-29  1
2016-04-30  0
2016-05-01  0
2016-05-02  0
2016-05-03  1
2016-05-04  0
2016-05-05  0
2016-05-06  0

那么如何确保在函数中使用了具有相应分位数列(在本例中 B_u)的正确列?

不清楚 "B_l" 应该在函数中的什么地方使用,因为自定义函数中没有使用 OP。除此之外,如果 'Data' 的列名与 "B_u" 的顺序不同,我们可以通过将 "B_u" 的 names 指定为相同的顺序"Data" 中的列索引,即 Data[, names(B_u)]。接下来要纠正的是使 "B_u" 和 "Data" 的长度相同。我们通过按 "Data" 中的行数复制 "B_u" 的每一列来做到这一点。在这里,我们使用 col 获取 "Data" 的列索引来进行复制。由于现在长度相等,我们可以 > 得到一个逻辑矩阵,我们通过与 0 求和强制转换为二进制。

test_a <- function(x, l, u){
    (x[, names(u)] > u[col(x[, names(u)])]) + 0
  }
test_a(Data, B_l, B_u)  
#            C1 C2
#2016-04-28  0  0
#2016-04-29  1  0
#2016-04-30  0  0
#2016-05-01  0  0
#2016-05-02  0  0
#2016-05-03  1  1
#2016-05-04  0  1
#2016-05-05  0  0
#2016-05-06  0  0