R Programming Fundamentals
上QQ阅读APP看书,第一时间看更新

Dataframes

A dataframe in R is a 2D object where the columns can contain data of different classes and types. This is very useful for practical data storage.

Dataframes can be created by using as.data.frame() on applicable objects or by column- or row-binding vectors using cbind.data.frame() or rbind.data.frame(). Here's an example where we can create a list of nested lists and turn it into a data frame:

list_for_df <- list(list(1:3), list(4:6), list(7:9))
example_df <- as.data.frame(list_for_df)

example_df will have three rows and three columns. We can set the column names just as we did with the matrix, though it isn't common practice in R to set the row names for most analyses. It can be demonstrated by the following code:

colnames(example_df) <- c("one", "two", "three")

We have covered a few of the key data structures in R in this section, and we have seen how to create and manipulate them. Let's try a few examples.