R中的for循环中的切换功能失败

时间:2018-08-05 13:56:28

标签: r for-loop switch-statement

我在R中的for循环中找不到切换功能的问题。有两个向量:付款金额和付款周期,编码为整数。我需要付款一年。如果付款被编码为一个月的4,例如,我会将其乘以12。如果代码为6,为一个一年,我将其乘以1。该函数将查看具有周期的向量,并且相应地调整付款。结果,我得到了不同长度的向量作为输入向量。它在循环内的某个地方失败了,但我不知道在哪里!您可以在下面找到相关代码。代码的相关部分是for循环。

toyear <- function(input, input2 = paste(substr(input, 1, 1), 
as.character(as.numeric(gsub(input, pattern = "X(\\d*)", rep="\\1"))+1), 
sep="")) {
  colInd1 <- which(colnames(data.scf.x) == input)
  colInd2 <- which(colnames(data.scf.x) == input2)

  if (any(!(is.element(data.scf.x[,colInd2], periodicityCodes)))) {
    stop("Something wrong with the periodicity variable, please reconsider")
  } 
  else {
    result <- numeric()
    test <- numeric()
a <- as.numeric(data.scf.x[,colInd1])
b <- as.numeric(data.scf.x[,colInd2])
for (i in 1:length(a)) {
  if (is.null(b[i])) {a[i] <- NA}
  else {
  switch(as.character(b[i]),
         "1" = {result[i] <- a[i]*365},
         "2" = {result[i] <- a[i]*52},
         "3" = {result[i] <- a[i]*36},
         "4" = {result[i] <- a[i]*12},
         "5" = {result[i] <- a[i]*4},
         "6" = {result[i] <- a[i]},
         "7" = {result[i] <- NA},
         "8" = {result[i] <- a[i]},
         "9" = {result[i] <- NA},
         "10" = {result[i] <- NA},
         "11" = {result[i] <- a[i]*2},
         "12" = {result[i] <- a[i]*6},
         "13" = {result[i] <- a[i]/3},
         "14" = {result[i] <- NA},
         "15" = {result[i] <- NA},
         "16" = {result[i] <- a[i]/7},
         "17" = {result[i] <- NA},
         "18" = {result[i] <- NA},
         "19" = {result[i] <- NA},
         "20" = {result[i] <- a[i]*5},
         "21" = {result[i] <- NA},
         "22" = {result[i] <- NA},
         "23" = {result[i] <- a[i]*13},
         "24" = {result[i] <- a[i]*8.6},
         "25" = {result[i] <- a[i]/2},
         "26" = {result[i] <- a[i]/4},
         "27" = {result[i] <- a[i]/5},
         "28" = {result[i] <- a[i]/10},
         "29" = {result[i] <- NA},
         "30" = {result[i] <- a[i]/7},
         "31" = {result[i] <- a[i]*24},
         "32" = {result[i] <- a[i]/8},
         "33" = {result[i] <- NA}
         )
        test[i] <- i
    }
  }
  cbind(result, test)
  }
}

以下数据示例。它是32 000行长。左列是付款,右列是代码。例如6意味着指定了一年的付款。

enter image description here

0 个答案:

没有答案