swapped sapply loops to vapply, for a speed increase