简体   繁体   中英

Regression in data frame in R

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 .

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)

 

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