我试图在另一个表中对列进行求和,并根据许多条件将其放在我当前的表中。
table1 <- tribble(~company_id,~date,
1,"2018-01-02",
1,"2018-01-03",
2,"2018-01-02",
2,"2018-01-03")
table2 <- tribble(~other_id, company_id,~date_created,~max_rank,rank,date_closed,
1,1,"2018-01-02",20,2,NA,
1,1,"2018-01-03",22,1,NA,
2,2,"2018-01-02",20,5,NA,
2,2,"2018-01-03",22,4,NA)
我想在表1中创建一个新列,它将输入以下公式:
= sum( (max_rank-rank)/(max_rank-1))
但仅限于:
(date<=date_created, date>(date_created+20), date<date_closed, max_rank-1!=0, rank!=0)
编辑
我希望实现的输出应该如下所示:
Table 1
| company id | date | cc score |
---------------------------------------
| 1 | 2018-01-02 | 0.9473 |
| 1 | 2018-01-03 | 1.9473 |
| 2 | 2018-01-02 | 0.7895 |
| 2 | 2018-01-03 | 1.6466 |
第一个可以计算为(20-2)/(20-1)= 0.9473第二个计算为(20-2)/(20-1)+(22-1)/(22-1)= 1.9473
您可以使用dplyr包。请尝试以下代码:
> library(dplyr)
> cbind(table1,table2)%>%inner_join(table1)%>%inner_join(table2)%>%filter(date<=date_created|date>(date_created+20)&max_rank-1!=0&rank!=0)%>%mutate(cc_data=(max_rank-rank)/(max_rank-1))%>%group_by(company_id)%>%mutate(cc_data=cumsum(cc_data))%>%select(company_id,date,cc_data)
请建议比这更好的解决方案。
这似乎有效:
table1[, cc_score := table2[table1,
on = .(company_id = company_id, date_created<=date, date_created_pls_20>date),
sum(ifelse(!is.na(rank) & (is.na(date_closed) | date_closed>date),
((max_rank-rank)/(max_rank-1)), 0)),
by = .EACHI][["V1"]]]
其中date_created_pls_20
是一个采用date_created
列的列,只需添加20