a few may have some mental disease (schizophrenia, bipolar disorder, for example) in which their reality may have been...askew, at the time the crime was committed.
Sometimes there's evidence to believe that those individuals didn't know the difference between right and wrong or didn't realize what they were doing because they had a break from reality.
If a court determines that they are not mentally responsible for their actions (because they are insane) then they go to the mental hospital instead of jail.
The ones going to a mental health facility either took a psych exam before trial (someone who is legally insane cannot stand trial and is hospitalized until able to stand trial) or they used the defense of 'insanity' which means that they were legally incapable of forming intent and understanding the nature of their crime, and a jury or judge bought the defense.