不能 return 基于参数的数据框中的值

Can't return a value from dataframe based on parameter

如果这是一个非常直接或重复的问题,我深表歉意,但我似乎无法获得或找到正确的解决方案。

我只是想 return 一个基于输入的函数的速率。所以如果我的数据框是:

   January   0.02
  February   0.04
     March   0.06
     April   0.08
       May   0.10
      June   0.12
      July   0.14
    August   0.16
 September   0.18
   October   0.20
  November   0.22
  December   0.24

我正在尝试 return 基于输入的增长。所以调用 monthly_growth(August) 应该 return 0.16.

如果这是一个基本问题并且非常简单,我深表歉意,但我似乎无法解决 - 提前致谢。

简单示例程序:

mon <- c("January","February","March","April","May","June","July","August","September","October","November","December")
rate <- c(0.02,0.04,0.06,0.08,0.10,0.12,0.14,0.16,0.18,0.20,0.22,0.24)

#create the dataframe to use for lookups
df <- data.frame(mon,rate)

#custom function - returns the rate for the month passed in.  No error checking
monthly_growth <- function(theMonth){
  return(df[df$mon==theMonth,"rate"])
}

#example usage
monthly_growth("August")
monthly_growth("October")

另一种选择,如果您只使用月份作为切换到汇率的输入,您可以使用 switch 函数:

getRate <- function(month) {
  switch(month,
         January = 0.02,
         February = 0.04,
         March = 0.06,
         April = 0.08,
         May = 0.1,
         June = 0.12,
         July = 0.14,
         August = 0.16,
         September = 0.18,
         October = 0.2,
         November = 0.22,
         December = 0.24,
         "Invalid month.")
}

getRate("August")
# [1] 0.16
getRate("hello")
# [1] "Invalid month."

仅供参考,稍微费点功夫,您就可以使该函数适用于不同 "month" 值的任何大写和月份缩写的任何大写,带或不带引号:

getRate2 <- function(month) {
  month <- tolower(as.character(substitute(month)))
  month <- paste0(toupper(substr(month, 1, 1)), 
                  substr(month, 2, nchar(month)))
  if (month %in% month.abb) month <- month.name[match(month, month.abb)]
  getRate(month)
}    

getRate2(AUG)
# [1] 0.16
getRate2(Aug)
# [1] 0.16
getRate2(AugUST)
# [1] 0.16
getRate2("aug")
# [1] 0.16