Hands-On Geospatial Analysis with R and QGIS
上QQ阅读APP看书,第一时间看更新

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)