is.character should also be treated as factor
move function definition out of the loop