 # Print The Table In R: Create and Print

Today, we will learn how to print the table in the R programming language. To print the table in R, we will use the table(),  as.table(), and print() function in this article. See the syntax and example below to understand it better.

## What is the table in R

The table in R is used to summarize the values in some datasets. And we will use the table() and as.table() functions to create a table, and then we will use the print() function to print the table.

### The table() and as.table() function: The Syntax

table(data)
as.table(data)

Parameters

• data: The data is a vector dataframe, … which you want to convert to a table.

## How to print the table in R?

### Print the table with a vector

First, we will create a vector for this example as follows:

# Create a vector
x <- c(9, 5, 6, 3, 4, 6)

# View a vector
x

Output

 9 5 6 3 4 6

Then, we will use the table() function to convert a vector to the table and use the print() function to print the table.

# Create a vector
x <- c(9, 5, 6, 3, 4, 6)

# Convert to table
tb <- table(x)

# Print the table
tb

Output

x
3 4 5 6 9
1 1 1 2 1

The table shows that the numbers “3”, “4”, “5”, and “9” each appear once in the position column, but “6” appears twice.

### Print the table with a data frame

In this example, we have a data frame below

# Create a data frame
df <- data.frame(
ID = c(1:6),
Math = c(9, 8, 9, 7, 8, 9),
English = c(8, 8, 9, 8, 7, 10)
)

# View a data frame
df

Output

  ID Math English
1  1    9       8
2  2    8       8
3  3    9       9
4  4    7       8
5  5    8       7
6  6    9      10

The count of each distinct value in the location column may be summarized using the table() function as follows:

# Create a data frame
df <- data.frame(
ID = c(1:6),
Math = c(9, 8, 9, 7, 8, 9),
English = c(8, 8, 9, 8, 7, 10)
)

# Create a table
tb1 <- table(df$Math) # Print the table with Math column cat("The table is:\n") tb1 Output The table is: 7 8 9 1 2 3 From the table, we can see that the “7” number appears 1 time, the “8” number appears 2 times in the position column, and ‘9’ appears 3 times. ### Print Two-Way Table Here, if you want to Print a Two-Way table, you can follow the steps below • First, we will use the data frame created above in this example. • Then, we use the table() function to create a table with Math and English columns. • Finally, we use the print() function to print the two-way table. Check out the code example below # Create a data frame df <- data.frame( ID = c(1:6), Math = c(9, 8, 9, 7, 8, 9), English = c(8, 8, 9, 8, 7, 10) ) # Create a table tb <- table(df$Math, df\$English)

# Print the table with the Math column
cat("The table is:\n")
tb

Output

The table is:
7 8 9 10
7 0 1 0  0
8 1 1 0  0
9 0 1 1  1

## Summary

In conclusion, this article helps you discover how to print the table in R and solve your problem. If you have any questions, do write a comment below.

Have a great day!

Posted in R