R Data Frames
A data frame is a table with rows and columns. Each column holds values of one type.
Build a small table
Two named columns build a table with three rows. Each row pairs one name with one age.
df <- data.frame(name = c("Ana", "Bo", "Cy"), age = c(30, 25, 41))
print(df)Count rows and columns
nrow counts the records in the table. ncol counts the variables.
df <- data.frame(name = c("Ana", "Bo", "Cy"), age = c(30, 25, 41))
print(nrow(df))
print(ncol(df))Columns with different lengths
One column holds three values and the other holds two. The build stops with an error about the differing row counts.
df <- data.frame(a = 1:3, b = 1:2)Example
shelf <- data.frame(title = c("Dune", "Emma", "Hobbit"), pages = c(412, 474, 310))
print(shelf)
print(nrow(shelf))Key points
- data.frame() builds a table from named columns.
- Each row is one record.
- Each column is one variable.
- A column is a vector, so every value in it shares one type.
- All columns must hold the same number of values.
- nrow() counts the records and ncol() counts the variables.
In this example, a data frame holds three book records. Each row pairs one title with its page count and nrow reports three rows.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What happens when one column has three values and another has two?