Thanks for your message, I can give you the data and the code, it isn't sensitive at all hahahaha.

The database I have done is like this:

Equipo Rival Jornada LoV Marcados Recibidos Resultado Puntos

1 Villarrubia Villanovense 1 L 0 3 P 0

2 Villanovense Villarrubia 1 V 3 0 G 3

3 Socu Badajoz 1 L 1 1 E 1

4 Badajoz Socu 1 V 1 1 E 1

5 Melilla Villarrobledo 1 L 3 0 V 3

6 Villarrobledo Melilla 1 V 0 3 D 0

7 Merida Talavera 1 L 0 1 D 0

8 Talavera Merida 1 V 1 0 V 3

9 Donbe Extremadura 1 L 1 2 D 0

10 Extremadura Donbe 1 V 2 1 V 3

Where the important variables are Equipo (team), Rival and Puntos (Points).

The table is ordered in first place by the points won by each team, but if there is a tie between two or more teams we see the head to head matches.

For example, now Donbe and Talavera have 20 points each one but Donbe is in a better position than Talavera because in the matches between then the results were:

Donbe 2 Talavera 0

Talavera 1 Donbe 1

Of course we can have 2, 3 or more teams with the same amount of points.

So, I can order the teams by the points won and I can make the tiebreaker function (the one I posted yesterday) but I dont know how to put both together.

For ordering the teams we can use:

```
l=summarise_at(group_by(datos,Equipo),vars(Puntos),funs(sum))
l=arrange(l, -Puntos)
```

The real tiebreaker function I have is:

```
desempate=function(datos2,empatados){
datos3=filter(datos2,Equipo %in% empatados,
Rival %in% empatados)
datos3$goalaverage=datos3$Marcados-datos3$Recibidos
if(dim(datos3)[1]==
4*factorial(length(empatados))/(2*factorial(length(empatados)-2))){
datos3=filter(datos2,Equipo %in% empatados,
Rival %in% empatados)
datos3$goalaverage=datos3$Marcados-datos3$Recibidos
m=summarise_at(group_by(datos3,Equipo),vars(Puntos,goalaverage),funs(sum))
m=arrange(m, -Puntos,-goalaverage)
}else{
datos2$goalaverage=datos2$Marcados-datos2$Recibidos
datos2=transform(datos2,averagecum= ave(goalaverage,Equipo, FUN =function(x) cumsum(x)))
m=summarise_at(group_by(datos2,Equipo),vars(averagecum),funs(last))
datos3=filter(m,Equipo %in% empatados)
m=arrange(datos3,-averagecum)
}
return(m)
}
```

Its not very important but if the teams tied have not played all the matches between the other ones the tiebreaker function would be the difference between scored and received goals.

Sorry for bad English and for bad programming I hope you have understood me and you could help me.

Thank you