官术网_书友最值得收藏!

Lists

A list is different from a vector because it can hold many different types of R objects inside it, including other lists. If you have experience programming in another language, you may be familiar with lists, but if not, don't worry! You can create a list in R using the list() function, as shown in the following example:

L1 <- list(1, "2", "Hello", "cat", 12, list(1, 2, 3))

Let's walk through the elements of this list. First, we have the number 1. Then, a character string, "2", followed by the character string "Hello", the character string "cat", the number 12, and then a nested list, which contains the numbers 1, 2, and 3.

Accessing these different parts of the list that we just created is slightly different—now, you are using list indexing, which means using double square brackets to look at the different items. 

You'll need to enter L1[[1]] to view the number 1 and L1[[4]] to see "cat".

To get inside the nested list, you'll have to use L1[[6]][1] to see the number 1. L1[[6]] gets us to the nested list, located at position 6, and L1[[6]][1] allows us to access the first element of the nested list, in this case, number 1. The following screenshot shows the output of this code:

Lists can also be changed into other data structures. We could turn a list into a dataframe, but this particular list, because it contains a nested list, will not coerce to a vector. The following code demonstrates this:

L1_df <- as.data.frame(L1)
class(L1_df)
L1_vec <- as.vector(L1)
class(L1_vec)

The following screenshot shows the output of this code:

主站蜘蛛池模板: 辛集市| 阿勒泰市| 清流县| 通道| 和林格尔县| 永川市| 大新县| 大埔县| 衡阳市| 内黄县| 翁牛特旗| 石楼县| 陵川县| 大厂| 革吉县| 揭东县| 吉林省| 车险| 雷州市| 五原县| 福海县| 瑞金市| 巴彦淖尔市| 丽江市| 鲁山县| 桐乡市| 神池县| 桓仁| 武穴市| 区。| 扎鲁特旗| 永修县| 平安县| 余江县| 广德县| 龙山县| 邢台市| 阿拉善左旗| 鲁甸县| 宁城县| 开原市|