• Post author:
• Post category:R Programming

How to convert a table to a data frame in R? You can use the `as.data.frame()`to convert the given data from the table to the data frame. When working with tabular data in R, you may need to convert tables to data frames for further analysis or visualization. Tables in R can be created using the `table()` or `as.table()` functions, and then converted to data frames using functions like `as.data.frame()` and `as.data.frame.matrix()`.

In this article, I will cover various methods for converting tables to data frames in R, including handling NA values and multi-dimensional tables.

Key points-

• Use the `table()` function to create contingency tables from raw data by counting the occurrences of unique values in one or more vectors.
• Convert tables to data frames using the `as.data.frame()` function for basic one-dimensional or two-dimensional tables.
• When creating tables, handle NA values using the `useNA = "ifany"` parameter to ensure they are included in the table and subsequently in the data frame.
• Convert multi-dimensional tables to data frames using the `as.data.frame.matrix()` function to preserve the structure of rows and columns.
• Convert matrices to tables using the `as.table()` function and then convert these tables to data frames using `as.data.frame.matrix()` or other suitable functions.
• Create contingency tables (cross-tabulations) to study the relationship between two or more categorical variables and convert these tables to data frames for further analysis.
• Use functions like `as.data.frame.matrix()` for complex table structures, particularly when dealing with multi-dimensional data.

## Convert Table to Data Frame using R as.data.frame()

To convert a simple frequency table to data frame using the as.data.frame() function. Let’s create the character vector and pass it into the `table()` function to convert it from vector to table. The `table()` function creates a contingency table from raw data by counting the occurrences of unique values in one or more vectors.

``````
# Convert table to data frame
# Create a sample vector
data <- c("A", "B", "C", "D", "E", "F")

# Create a table
table_data <- table(data)
print("Create table:")
print(table_data)
print("Get the type:")
print(class(table_data))
``````

Yields below output.

To convert the above table into a data frame using the `as.data.frame()` function, simply pass the table into this function. It will convert the table into a data frame where the columns represent the table values and their frequencies.

``````
# Convert table to data frame uisng as.data.frame() function
df <- as.data.frame(table_data)
print("After converting table to data frame:")
print(df)
print("Get the type:")
print(class(df))
``````

Yields below output.

## Convert the Contingency Table to a Data Frame in R

Alternatively, you can convert a contingency table to a data frame in R using the `as.data.frame()` function. A contingency table, also known as a cross-tabulation or crosstab, is a type of table used in statistics to display the frequency distribution of variables.

Let’s create two vectors and use these vectors to create a contingency table. Then, we will use `as.data.frame()` to convert the contingency table to a data frame.

``````
# Convert contingency table to data frame
# Create sample data vectors
gender <- c("Male", "Male", "Female", "Female", "Male", "Female")
product <- c("A", "B", "A", "B", "A", "B")

# Create a contingency table
table_data <- table(gender, product)
print("Create table:")
print(table_data)
print("Get the type:")
print(class(table_data))

# Convert the table to a data frame
df <- as.data.frame(table_data)
print("After converting table to data frame:")
print(df)
print("Get the type:")
print(class(df))
``````

Yields below output.

``````
# Output:
[1] "Create table:"
product
gender   A B
Female 1 2
Male   2 1

[1] "Get the type:"
[1] "table"

[1] "After converting table to data frame:"
gender product Freq
1 Female       A    1
2   Male       A    2
3 Female       B    2
4   Male       B    1

[1] "Get the type:"
[1] "data.frame"
``````

## Convert Table with NA value to Data Frame

To handle NA values in a table and convert it to a data frame, use the `table()` function with the parameter `useNA = "ifany"` to include NA values in the table. Then, convert the table to a data frame using the `as.data.frame()` function, which will return a data frame that includes the NA values.

``````
# Convert table to data frame
# Create a sample vector with NA values
data <- c("A", "B", NA, "C", "B", "A", NA)

# Create a table
table_data <- table(data, useNA = "ifany")
print("Create table:")
print(table_data)
print("Get the type:")
print(class(table_data))

# Convert the table to a data frame
df <- as.data.frame(table_data)
print("After converting table to data frame:")
print(df)
print("Get the type:")
print(class(df))
``````

Yields below output.

``````
# Output:
[1] "Create table:"
data
A    B    C <NA>
2    2    1    2

[1] "Get the type:"
[1] "table"

[1] "After converting table to data frame:"

data Freq
1    A    2
2    B    2
3    C    1
4 <NA>    2

[1] "Get the type:"
[1] "data.frame"
``````

## Use as.data.frame.matrix() Function

Similarly, you can use the `as.data.frame.matrix()` function to convert a table to a data frame. This function is typically used for converting matrices and multi-dimensional tables into data frames, but it doesn’t work directly for one-dimensional tables (like those created from a single vector).

First, create a table using the `table()` function. Then, convert this table to a data frame using `as.data.frame.matrix()`, which preserves the structure of rows and columns, with the counts represented as columns.

Let’s use `as.data.frame.matrix()` to convert a table to a data frame while maintaining the original row and column structure.

``````
# Convert table to data frame uisng as.data.frame.matrix() function
data = data.frame(x=c(1,2,3,4,5),
y=c(6,7,8,9,10))

# Create a table
table_data <- table(data)
print("Create table:")
print(table_data)
print("Get the type:")
print(class(table_data))

# Convert the table to a data frame
df <- as.data.frame.matrix(table_data)
print("After converting table to data frame:")
print(df)
print("Get the type:")
print(class(df))
``````

Yields below output.

``````
# Output:
[1] "Create table:"
y
x   6 7 8 9 10
1 1 0 0 0  0
2 0 1 0 0  0
3 0 0 1 0  0
4 0 0 0 1  0
5 0 0 0 0  1

[1] "Get the type:"
[1] "table"

[1] "After converting table to data frame:"

6 7 8 9 10
1 1 0 0 0  0
2 0 1 0 0  0
3 0 0 1 0  0
4 0 0 0 1  0
5 0 0 0 0  1

[1] "Get the type:"
[1] "data.frame"
``````

## Use data.frame() Function and rbind()

In this example, I will use the `as.table()` function to convert an existing object, such as a matrix, into a table. This is particularly useful when you already have data in matrix form and want to treat it as a table. First, create a matrix, then convert the matrix to a table using the `as.table()` function, and finally convert it to a data frame using `data.frame()` and `rbind()`.

``````
# Convert table to data frame using data.frame() and rbind()
# Create matrix
data <- matrix(1:8, ncol=4, byrow=TRUE)

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

# Create a table
table_data <- as.table(data)
print("Create table:")
print(table_data)
print("Get the type:")
print(class(table_data))

# Convert the table to a data frame
df <- data.frame(rbind(table_data))
print("After converting table to data frame:")
print(df)
print("Get the type:")
print(class(df))
``````

Yields below output.

``````
# Output:
[1] "Create table:"
A B C D
F 1 2 3 4
G 5 6 7 8

[1] "Get the type:"
[1] "table"

[1] "After converting table to data frame:"
A B C D
F 1 2 3 4
G 5 6 7 8

[1] "Get the type:"
[1] "data.frame"
``````

## Conclusion

In this article, I explained how converting tables to data frames in R is essential for data analysis and visualization. By using functions like `as.data.frame()`, `as.data.frame.matrix()`, and `data.frame(rbind())`, you can efficiently transform tables into data frames while preserving their structure and handling various data types. I also demonstrated how to use the `table()` and `as.table()` functions to convert different R objects to tables.

Happy Learning!!