Convert Table to Data Frame in R (Example)
In this R programming tutorial you’ll learn how to convert a table to a data.frame.
The page looks as follows:
It’s time to dive into the programming part…
Creation of Example Data
In the example of this R tutorial, we’ll use the following contingency table as input data:
set.seed(642) # Create example table my_tab <- table(x1 = round(rnorm(100)), x2 = round(rnorm(100))) my_tab # Print table to console # x2 # x1 -2 -1 0 1 2 # -2 0 3 2 3 0 # -1 2 3 13 6 3 # 0 1 5 16 11 1 # 1 2 10 9 4 0 # 2 1 0 1 3 0 # 3 0 0 1 0 0
Our table contains the cross tabulation of two rand normally distributed variables.
Example: Converting table to data.frame
We can convert our example table to the data.frame class with the as.data.frame.matrix function. Consider the following R code:
my_dataframe <- as.data.frame.matrix(my_tab) # Convert table to data frame my_dataframe # Print data.frame to console # -2 -1 0 1 2 # -2 0 3 2 3 0 # -1 2 3 13 6 3 # 0 1 5 16 11 1 # 1 2 10 9 4 0 # 2 1 0 1 3 0 # 3 0 0 1 0 0
As you can see based on the output of the RStudio console (or by applying the class function to our new data object), we have successfully converted our table to a data.frame object in the R programming language.
Video, Further Resources & Summary
Have a look at the following video of the Statistics Globe YouTube channel. I’m explaining the R programming syntax of this article in the video:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may have a look at the related tutorials on my website.
To summarize: In this R tutorial you learned how to convert a crosstab to a data frame. Note that the same approach would work to change the column vectors of frequency tables in R. If you have further questions, let me know in the comments.
Statistics Globe Newsletter