无法根据参数从数据框中返回值

时间:2016-07-28 17:45:42

标签: r function lookup

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

我只是想根据输入从函数返回一个速率。所以如果我的数据框是:

   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

我试图根据输入返回增长。所以调用monthly_growth(August)应该返回0.16。

我很抱歉,如果这是一个基本问题并且非常直截了当,但我似乎无法将其拉出来 - 先谢谢。

2 个答案:

答案 0 :(得分:1)

简单示例程序:

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")

答案 1 :(得分:1)

另一种选择,如果您只使用月份作为输入来切换到某个费率,则可以使用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."

只是一个FYI,有一点点,您可以使该功能适用​​于不同“月”值的任何大写,以及月份缩写的任何大小写,带或不带引号:

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