How to Create Tables in R (With Examples)

There are two ways to quickly create tables in R:

Method 1: Create a table from existing data.

```tab <- table(df\$row_variable, df\$column_variable)
```

Method 2: Create a table from scratch.

```tab <- matrix(c(7, 5, 14, 19, 3, 2, 17, 6, 12), ncol=3, byrow=TRUE)
colnames(tab) <- c('colName1','colName2','colName3')
rownames(tab) <- c('rowName1','rowName2','rowName3')
tab <- as.table(tab)
```

This tutorial shows an example of how to create a table using each of these methods.

Create a Table from Existing Data

The following code shows how to create a table from existing data:

```#make this example reproducible
set.seed(1)

#define data
df <- data.frame(team=rep(c('A', 'B', 'C', 'D'), each=4),
pos=rep(c('G', 'F'), times=8),
points=round(runif(16, 4, 20),0))

#view head of data

team pos points
1    A   G      8
2    A   F     10
3    A   G     13
4    A   F     19
5    B   G      7
6    B   F     18

#create table with 'position' as rows and 'team' as columns
tab1 <- table(df\$pos, df\$team)
tab1

A B C D
F 2 2 2 2
G 2 2 2 2
```

This table displays the frequencies for each combination of team and position. For example:

• 2 players are on position ‘F’ on team ‘A’
• 2 players are on position ‘G’ on team ‘A’
• 2 players are on position ‘F’ on team ‘B’
• 2 players are on position ‘G’ on team ‘B’

And so on.

Create a Table from Scratch

The following code shows how to create a table with 4 columns a 2 rows from scratch:

```#create matrix with 4 columns
tab <- matrix(rep(2, times=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 2 2 2 2
G 2 2 2 2```

Notice that this table is the exact same as the one created in the previous example.

May 13, 2024
April 25, 2024
April 19, 2024
April 18, 2024
April 18, 2024

2 Replies to “How to Create Tables in R (With Examples)”

1. Farrel Buchinsky says:

Thank you for this tutorial. Alas, I like neither method. Often I have tiny, and I mean tiny, little personal projects. For example, sometimes I let my hot tub temperature decline to save electricity. I start the reheating process and I take a couple of time points to figure out its rate of heating. I then have about 5 time points (time, temperature). It is easiest to enter in a table rather than futzing with typed out vectors. At a future date I will probably do it again and thus append date to the table. One way to do this would be to open a spreadsheet (eg LibreOffice on desktop or googlesheets on web) and then import from there. However, I think it would be easier to create from something such as the editData package or the DataEditR package. Are either of those packages useful for creating the table?

2. CJ says:

I tried doing this with more than 6 rows, but R still shows 6 rows. How do I fix this?