如何应用"复杂的"用户定义的函数在tibble

时间:2017-05-05 16:24:53

标签: r function mutate tibble

我已经搜索了这个(看似简单的)问题的答案,但是空洞,所以我希望有人可以帮助我或指出我正确的方向。

我有一个相当复杂的子模型,我想应用于数据集,但如果我只是使用mutate,我会收到错误Variables must be length 1 or 21.添加rowwise()似乎不会影响它。

让我用下面这个问题的愚蠢说明:

myData <- tibble(x=10:20, y=c("a", "b","a", "b","a", "b","a", "b","a", "b","a"))

staticData <- tibble(x=0:100, y=c("a"),f=x/100) %>% union (tibble(x=0:100, y=c("b"),f=x/1000))

ComplicatedFunction <- function(mystaticData, myx, myy) {
  #make the base table 
  myBaseTable <- tibble(
    y = myy,
    x = c(myx:(myx + 20)) 
  )
  #add  f rates
  myBaseTable <- left_join(myBaseTable,mystaticData)
  #add stuff
  myBaseTable <- myBaseTable %>% 
    mutate(z = 1 - (f * 0.8)) %>% 
    mutate(zCumulative = cumprod(z)) 
  #Calculate the thing
  myCalculatedThing <- sum(myBaseTable$zCumulative)

  return(myCalculatedThing)
}

#This is what I want to do 
myData %>% mutate(newcol = ComplicatedFunction(mystaticData = staticData, 
                                               myx = x, 
                                               myy = y))
#this works
ComplicatedFunction(mystaticData = staticData, 
                    myx = 19, 
                    myy = "b")
ComplicatedFunction(mystaticData = staticData, 
                    myx = 20, 
                    myy = "a")

#This works (but would be silly as I want the function to be evaluated for each line)
myData %>% mutate(newcol = ComplicatedFunction(mystaticData = staticData, 
                                               myx = 15, 
                                               myy = "a"))

#This no longer works, but I dont understand what I am doing wrong
myData %>% mutate(newcol = ComplicatedFunction(mystaticData = staticData, 
                                               myx = x, 
                                               myy = "a"))

#I tried rowwise(), but this doesnt seem to work either 
myData %>% rowwise() %>% mutate(newcol = ComplicatedFunction(mystaticData = staticData, 
                                               myx = x, 
                                               myy = y))

我希望有人可以向我解释我在这里做错了什么。

非常感谢提前!

西尔

1 个答案:

答案 0 :(得分:2)

您可以使用partial

创建新功能
library(purrr)
newCF <- partial(ComplicatedFunction, mystaticData = staticData)
myData %>% rowwise() %>% mutate(newcol = newCF(myx = x, 
                                           myy = y))