Tables are a data structure in [[R]] commonly used as a [[contingency table]] in statistical analysis. Use `as.table()` to create a table from a `matrix`. For a more general data structure for tabular data, see [[data.frame]].
How to originally construct a table in [[R]] depends on the initial format of your data.
## from scratch
Let's say you have a table in print form or any other way that is not accessible digitally. We'll first create vectors for each row or column and then use `rbind` or `cbind` to combine into a matrix and `as.table` to create a table. Row or column names will be the variable names of each vector, but can also be set with the `rownames` and `colnames` commands.
```R
# create matrix with 4 columns and 4 rows
bag1 <- c(14, 18, 11, 6)
bag2 <- c(10, 20, 12, 9)
bag3 <- c(13, 14, 15, 8)
bag4 <- c(15, 15, 10, 10)
# assign to table
data <- rbind(bag1, bag2, bag3, bag4, bag5, bag6)
my_table <- as.table(data)
# specify the column names and row names of matrix
colnames(data) <- c('candyA','candyB','candyC','candyD')
rownames(data) <- c('bag1','bag2','bag3','bag4')
# display
my_table
```
## from clipboard
A handy trick can be to copy the table from the source and read the pasted text into R. Use the `read.csv` command and update the `sep` parameter to the correct one for your data. This will return a `data.frame` object. In the example below, the data are tab separated.
```R
read.csv(
text=
" Candy A Candy B Candy C Candy D
Bag 1 14 18 11 6
Bag 2 10 20 12 9
Bag 3 13 14 15 8
Bag 4 15 15 10 10
", sep="\t"
)
```
## building a table
Use a [tibble](https://tibble.tidyverse.org/reference/tibble.html) to create a table column-wise in [[R]].
```
x <- c(...)
y <- c(...)
t <- tibble(x, y)
```
Each column will have the name of the variable; ("x", "y") in this case.
Rename columns with `names()`.
```R
names(t) = c("x", "y")
```
Using `read_table` returns a tibble.
```R
mpg.data = read_table("auto-mpg.data")
names(mpg.data) = c("mpg", "cylinders", "displacement", "horsepower", "weight",
"accel", "model_year", "origin", "car_name")
mpg.data$horsepower = as.numeric(mpg.data$horsepower)
mpg.data = na.omit(mpg.data)
```
Use a [tribble](https://tibble.tidyverse.org/reference/tribble.html) to create a table row-wise.
Other options include data.frame(), matrix(), as.table(), and data.table().
#rough