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

Lists

Now, items jan_price and mar_price have four elements, whereas june_price has three elements. So, we can't use a data frame in this case to store all of these values in a single variable. Instead, we can use lists. Using lists, we can get almost all the advantages of a data frame in addition to its capacity for storing different sets of elements (columns in the case of data frames) with different lengths:

all_prices_list2 = list(items, jan_price, mar_price, june_price)
all_prices_list2

We can now see that all_prices_list2 has a different structure than that of a data frame:

Accessing list elements can be done by either using [] or [[]] where the former gives back a list and the latter gives back element(s) in its original data type. We can get the values of jan_price in the following way:

all_prices_list2[2]

Using [], we are returned with the second element of all_prices_list2 as a list again:

Note that, by using [], what we get back is another list and we can't use different mathematical operations on it directly.

class(all_prices_list2[2])

We can see, as follows, that the class of all_prices_list2 is a list:

We can get this data in original data types (that is, a numeric vector) by using [[]] instead of []:

all_prices_list2[[2]]

Now, we get the second element of the list as a vector:

We can see that it is numeric and we can check further to confirm that it is numeric:

class(all_prices_list2[[2]])

The following result confirms that it is indeed a numeric vector:

We can also create categorical variables with factor().

Suppose we have a numeric vector x and we want to convert it to a factor, we can do so by following the code as shown as follows:

x = c(1, 2, 3)
x = factor(x)
class(x)
主站蜘蛛池模板: 莲花县| 石河子市| 景东| 龙泉市| 鹰潭市| 卢氏县| 和平县| 德令哈市| 乌恰县| 定陶县| 临江市| 四子王旗| 额敏县| 和政县| 沂水县| 崇义县| 冕宁县| 伊宁市| 离岛区| 和田县| 新沂市| 临泉县| 平利县| 宁乡县| 凤山县| 邢台市| 青河县| 衡南县| 织金县| 延安市| 铜鼓县| 县级市| 青川县| 五大连池市| 泽普县| 京山县| 调兵山市| 柳林县| 灌阳县| 静宁县| 航空|