问题
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
回答1:
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))
来源:https://stackoverflow.com/questions/43809701/how-to-apply-a-complicated-user-defined-function-on-each-element-of-a-tibble