The QWERTY keyboard layout first appeared in the Remington No. 2 typewriter in 1878 (Mark Twain was one of the first customers). The design had undergone iterations for a few years, rearranging letters based on telegraph operators' feedback. A study on letter-pair frequencies is said to have influenced it as well.
There are more optimal keyboard layouts. For example, Dvorak (patented 1936) requires less finger motion – making it faster, more comfortable, and less error-prone. But QWERTY hasn't changed much in the last 144 years.
Keyboard layouts are an example of path dependence. It explains a process that doesn't march steadily towards some predetermined equilibrium but instead gets stuck in local maxima. As a result, seemingly small decisions early on (like the width of a standard railroad gauge) have disproportionately large effects later on.