Reputation: 59
Hey I have following test data:
test = data.frame(Date = c(as.Date("2010-10-10"), as.Date("2010-10-10"), as.Date("2010-12-10"), as.Date("2010-12-10")), Rate = c(0.1, 0.15, 0.16, 0.2), FCF = c(100,200,150,250))
Now I want to group the data by Date, do linear regression FCF~Rate
in each group and then perform these regression in each group to get Value of this regression for each date and Rate. I have following code:
output = test %>% group_by(Date) %>% do(mod = lm(FCF ~ Rate, data = .))
output = test %>% left_join(output, by = "Date")
output = output %>% ungroup() %>% mutate(Value = predict(mod, newdata = Rate))
everything works fine without the last line because mod
is not a model but a list and I cant do prediction. What should I change?
EDIT: When I evaluate this code:
output = test %>% group_by(Date) %>%
do(mod = lm(FCF ~ Rate, data = .))
output = test %>% left_join(output, by = "Date")
output = output %>% ungroup()
I get:
The question is how can I use models from mod
column to calculate predicted value for Rates from column Rate
.
Upvotes: 2
Views: 61
Reputation: 887881
Here is one way
library(dplyr)
library(purrr)
test %>%
nest_by(Date) %>%
mutate(mod = list(lm(FCF ~ Rate, data = data))) %>%
ungroup %>%
mutate(out = map2(data, mod,
~ predict(.y, newdata = data.frame(Rate = .x$Rate))))
-output
# A tibble: 2 x 4
# Date data mod out
# <date> <list<tibble>> <list> <list>
#1 2010-10-10 [2 × 2] <lm> <dbl [2]>
#2 2010-12-10 [2 × 2] <lm> <dbl [2]>
If we need the 'Pred' column as well
library(tidyr)
out <- test %>%
nest_by(Date) %>%
mutate(mod = list(lm(FCF ~ Rate, data = data))) %>%
ungroup %>%
mutate(data = map2(data, mod, ~ .x %>%
mutate(Pred = predict(.y, newdata = cur_data())))) %>%
unnest(data)
Upvotes: 3