这可以在没有循环的情况下完成吗?

时间:2018-06-01 00:34:47

标签: r

我今天看不到矩阵......

获得此结果的更好方法是什么......

    date_bom    pmsector1 recommendation sec_returns
      <dttm>       <fctr>         <fctr>       <dbl>
1 2005-01-01 Apartment HB         SPREAD      0.1168
4 2005-01-01 Apartment LB         SPREAD     -.40174

从此输入数据(df)

    date_bom    pmsector1 recommendation sec_returns
      <dttm>       <fctr>         <fctr>       <dbl>
1 2005-01-01 Apartment HB            BUY -0.98328013
2 2005-01-01 Apartment HB           HOLD  0.39360700
3 2005-01-01 Apartment HB           SELL -1.10071321
4 2005-01-01 Apartment LB            BUY -0.07363028
5 2005-01-01 Apartment LB           HOLD  0.02747529
6 2005-01-01 Apartment LB           SELL  0.32811229

这是有效的,但它必须以更好,更少循环的方式实现。

dates<-unique(df$date_bom)
new = data.frame(date_bom=as.Date(character()),pmsector1=character(),recommenation=character(),spread=double())
for (date in seq(0:length(dates))){
  for(sector in unique(df$pmsector1)){
    buy <-df[which(df$pmsector1==sector & df$date_bom==dates[date] & df$recommendation=="BUY"),4]
    sell<-df[which(df$pmsector1==sector & df$date_bom==dates[date] & df$recommendation=="SELL"),4]
    update<-data.frame(list(dates[date], sector, "SPREAD", as.numeric(as.numeric(buy)-as.numeric(sell))))
    names(update)<-c("date_bom","pmsector1","recommendation","sec_returns")
    new<-rbind(new,update)
  }
}

1 个答案:

答案 0 :(得分:2)

library(tidyverse)
tbl <- read_csv(
"date_bom ,   pmsector1, recommendation, sec_returns
2005-01-01, Apartment HB,            BUY, -0.98328013
2005-01-01, Apartment HB,           HOLD,  0.39360700
2005-01-01, Apartment HB,           SELL, -1.10071321
2005-01-01, Apartment LB,            BUY, -0.07363028
2005-01-01, Apartment LB,           HOLD,  0.02747529
2005-01-01, Apartment LB,           SELL,  0.32811229"
)

tbl %>%
  spread(recommendation, sec_returns) %>%
  group_by(date_bom, pmsector1) %>%
  summarise(recommendation = "SPREAD", sec_returns = BUY - SELL)
#> # A tibble: 2 x 4
#> # Groups:   date_bom [?]
#>   date_bom   pmsector1    recommendation sec_returns
#>   <date>     <chr>        <chr>                <dbl>
#> 1 2005-01-01 Apartment HB SPREAD               0.117
#> 2 2005-01-01 Apartment LB SPREAD              -0.402

reprex package(v0.2.0)创建于2018-05-31。