[R] Convert dataframe to table with counts where column names become row names

David Winsemius dwinsemius at comcast.net
Thu Aug 6 22:39:47 CEST 2009


On Aug 6, 2009, at 1:14 PM, ghinkle wrote:

>
> Can anyone explain how best to go from a dataframe to a table (or  
> better yet
> a new dataframe) of counts, where the row names in the new table (or
> dataframe) are the column names of the original df.
>
> start w/
> DF1 =
>           Pos1  Pos2 Pos3 ....
> oligo1   G       C     A
> oligo2   U       U     A
> oligo3   G       C     C
> oligo4   C       G     U
> oligo5   A       A     G
> .....

 > apply(DF1, 2, table)
   Pos1 Pos2 Pos3
A    1    1    2
C    1    2    1
G    2    1    1
U    1    1    1


Since tables are really matrices, the t() operation would bring you to  
your goal:

 > t( apply(DF1, 2, table) )
      A C G U
Pos1 1 1 2 1
Pos2 1 2 1 1
Pos3 2 1 1 1


>
> End with
>
> DF2 =
>           G  A  U C
> Pos1   2   1 1 1
> Pos2   1  1  1  2
> Pos3  1  2  1  1
> ....
>
> I know how to generate the counts of each one column at a time using
> "table(DF1$Pos1)".
> Is there a way to do this in one step?  Should I just write a for  
> loop for
> each of the columns?
---

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list