Search code examples
pythonrpandascrosstab

Is there any function in R similar to pd.crosstab in python?


I am looking for a function in R similar to pd.crosstab in python where, I want to create contingency matrix between 2 columns based on the values of a third column's sum.

Example -

Column1 | Column2 | Column3
A       | X       | 1
A       | Y       | 2
A       | Z       | 3
B       | X       | 1
B       | Y       | 2
B       | Z       | 3

Output

  | X | Y | Z
A | 1 | 2 | 3
B | 1 | 2 | 3

Solution

  • The function is called crosstabs ie xtabs:

    xtabs(Column3~Column1+Column2, df)
           Column2
    Column1 X Y Z
          A 1 2 3
          B 1 2 3