简体   繁体   中英

How to apply a “complicated” user defined function on each element of a tibble

I have searched high and low for the answer to this (seemingly simple) problem, but came up empty so I hope someone can help me or point me in the right direction.

I have a fairly complicated submodel that I want to apply to a dataset, but if I just use use mutate I get an error Variables must be length 1 or 21. adding rowwise() doesnt seem to impact it.

Let me use the following silly illustration of the problem:

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

I hope someone can explain to me what I am doing wrong here.

Many thanks in advance!

Sylvain

You can do it by creating a new function using partial :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM