I wrote this code that does is the following.
In the table mo102
there are costs that I want to divide and add equally to the rows of the table table_reduced
that share the same values on some particular columns. Those columns are id_s
, t_hab
, p_d
.
The problem is that using a for loop is not optimal and takes a lot of time. Is there a solution using dplyr
to do this?
tblsin = as.data.frame(0, col.names = colnames(table_reduced))
lsin = length(mo102[[1]])
for (i in 1:lsin) {
ns <- mo102[[3]][i]
t_hab <- mo102[[4]][i]
p_d <- mo102[[5]][i]
cout_s <- mo102[[6]][i]
temp <- table_reduced %>% filter(., ID_S %in% ns & T_HAB %in% t_hab & P_D %in% p_d & code_b != "MO102")
len <- length(temp[[1]])
if (len != 0) {
temp <- mutate(temp, total_cost = total_cost + cout_s/len)
tblsin = bind_rows(tblsin, temp)
}
}
A mo102
table looks like this:
piece.agr DS_ESTETICO_PARTIDA ID_SINIESTRO TIPO_HAB_D DS_PARTE_D total_cost
3 ASE Directos 100210#000000986776904#2 ASE _DIVERS 160
table_reduced
looks like this:
ID_SINIESTRO piece.agr TIPO_HAB_D DS_PARTE_D DS_ESTETICO_PARTIDA code_bareme total_cost
<chr> <chr> <chr> <chr> <chr> <chr> <dbl>
2 100210#000000331493904#2 COC ASE _DIVERS Esteticos P003 264.60
5 100210#000000986776904#2 ASE ASE _DIVERS Directos PB101 94.20
The result I want is a table_reduced
where the data from total_cost
from the table mo102
is divided by two and added to each of the rows, since they have the same attributes.
Since 160 is the cost on mo120
, it is divided by 2 (number of identical rows) and added to these rows.
So like this:
ID_SINIESTRO piece.agr TIPO_HAB_D DS_PARTE_D DS_ESTETICO_PARTIDA code_bareme total_cost
<chr> <chr> <chr> <chr> <chr> <chr> <dbl>
2 100210#000000331493904#2 COC ASE _DIVERS Esteticos P003 344.60
5 100210#000000986776904#2 ASE ASE _DIVERS Directos PB101 174.20