Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 动态if-else“;测试“;或案例“当”;公式;从键值表?_R_Dynamic_Key Value - Fatal编程技术网

R 动态if-else“;测试“;或案例“当”;公式;从键值表?

R 动态if-else“;测试“;或案例“当”;公式;从键值表?,r,dynamic,key-value,R,Dynamic,Key Value,我试图在R中编写一个函数,它使用分位数断点的“key-value”data.frame返回基于输入值所属分位数的权重。以下是其中一个data.frames的示例: key1 <- data.frame(Boundary = c(0.01, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.22),

我试图在
R
中编写一个函数,它使用分位数断点的“key-value”data.frame返回基于输入值所属分位数的权重。以下是其中一个data.frames的示例:

key1 <- data.frame(Boundary = c(0.01, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 
                               0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.22), 
                   Weight = c(0,1, 3.5, 8, 15, 25, 37.5, 51.5, 65, 76.5, 85.5, 
                              91.5, 95, 97.5,99, 100))

FindInterval
会起到作用,请查看以精确设置限制:

getWeight <- function(x,key){
  key$Weight[findInterval(x,key$Boundary)]
}
getWeight(0.14,key1)
[1] 91.5

getWeight您应该使用
cut
为每次观察构建铲斗,然后使用铲斗位置分配重量。类似于
mybucket的东西
getWeight_Dynamic <- function(val, k = key1){

  qb <- c(0, k[["Boundary"]])
  w <- c()

  for(b in 1:length(qb)){

    if(val < qb[b+1] && val >= qb[b] ){
    w <- k[b-1, 2]
   } 
  }
  return(w)
}

sapply(val_vec, getWeight_Dynamic)
key2 <- data.frame(Boundary = c(0.1, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 
                               0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 
                               0.31, 0.32, 0.33, 0.330200000000004, 0.35, 0.42), 
                  Weight = c(0, 1, 2, 4, 7, 11, 16.5, 23.5, 32, 41.5, 51, 60, 
                             69, 77, 83.5, 89, 93, 95.5, 97, 98, 99, 100))
getWeight <- function(x,key){
  key$Weight[findInterval(x,key$Boundary)]
}
getWeight(0.14,key1)
[1] 91.5