How to Convert Table to Data Frame in R (With Examples)


You can use the following basic syntax to convert a table to a data frame in R:

df <- data.frame(rbind(table_name))

The following example shows how to use this syntax in practice.

Example: Convert Table to Data Frame in R

First, let’s create a table in R:

#create matrix with 4 columns
tab <- matrix(1:8, ncol=4, byrow=TRUE)

#define column names and row names of matrix
colnames(tab) <- c('A', 'B', 'C', 'D')
rownames(tab) <- c('F', 'G')

#convert matrix to table 
tab <- as.table(tab)

#view table 
tab

  A B C D
F 1 2 3 4
G 5 6 7 8

#view class
class(tab)

[1] "table"

Next, let’s convert the table to a data frame:

#convert table to data frame
df <- data.frame(rbind(tab))

#view data frame
df

  A B C D
F 1 2 3 4
G 5 6 7 8

#view class
class(df)

[1] "data.frame"

We can see that the table has been converted to a data frame.

Note that we can also use the row.names function to quickly change the row names of the data frame as well:

#change row names to list of numbers
row.names(df) <- 1:nrow(df)

#view updated data frame
df

  A B C D
1 1 2 3 4
2 5 6 7 8

Notice that the row names have been changed from “F” and “G” to 1 and 2.

Additional Resources

The following tutorials explain how to perform other common operations in R:

How to Convert Matrix to Vector in R
How to Convert List to Matrix in R
How to Convert Data Frame Column to Vector in R

Leave a Reply

Your email address will not be published.