Conversion of Matrix of Characters to a Matrix of Zeros and Ones based on Column Frequency
ClearAll[f0, f1, f2]
f0 = ArrayComponents[{#, First@Commonest@#}, 3, {x_, y_} :> Unitize[x /. y -> 0]] &
f0 @ m // MatrixForm // TeXForm
$\left( \begin{array}{cccccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 \\ 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\ 0 & 1 & 0 & 1 & 1 & 0 & 0 & 1 & 0 & 1 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 \\ \end{array} \right)$
Also:
f1 = Transpose[Replace[#, {Commonest[#, 1][[1]] -> 0, _ :> 1}, {1}] & /@ Transpose[#]] &;
f2 = Transpose[Unitize[# - Commonest[#][[1]]] & /@ ArrayComponents[Transpose @ # ]] &;
f0 @ m == f1 @ m == f2 @ m
True
{nRow,nCol}=Dimensions[m];
com = Flatten@Commonest[m] ;
Table[ m[[i,j]] = If[m[[i,j]]==com[[j]], 0, 1] , {i,nRow},{j,nCol}];
And now
MatrixForm[m]
ps. Thanks to JM hint, it is also possible to shorten this more by using Boole
instead of the If
above
Table[ Boole[ m[[i,j]] != com[[j]] ] , {i,nRow},{j,nCol} ];
(Turns out @kglr beat me to it with a nicer implementation of the same idea. I'll leave this up for the time being, as it might help us simple folk understand what all the _ :> 1
stuff is about.)
Get your replacement rules for each column:
rr = {#[[1]] -> 0, #[[2]] -> 1} & /@ (Commonest[#, 2] & /@ Transpose[m])
{{"T" -> 0, "C" -> 1}, {"T" -> 0, "A" -> 1}, {"A" -> 0, "T" -> 1}, {"A" -> 0, "G" -> 1}, {"G" -> 0, "A" -> 1}, {"G" -> 0, "A" -> 1}, {"C" -> 0, "T" -> 1}, {"C" -> 0, "T" -> 1}, {"C" -> 0, "T" -> 1}, {"C" -> 0, "A" -> 1}}
Apply them:
Transpose @ MapThread[ReplaceAll, {Transpose[m], rr}] // MatrixForm