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

lapply

In the previously mentioned power_function() function, we had to use a for loop to loop through all the values of the june_price column of the all_prices4 data frame. lapply allows us to define a function (or use an already existing function) over all the elements of a list or vector and it returns a list. Let's redefine power_function() to allow for the computation of different powers on elements and then use lapply to loop through each element of a list or vector and take the power of each of these elements on every iteration of the loop. lapply() has the following format:

lapply(data, function, arguments_of_the_function)
power_function2 = function(data, power){
data^power
}
lapply(all_prices4$june_price, power_function2, 4)

As we saw in the last output, all the prices of june_price are taken to the fourth power and are returned as a list:

What we get in return is a list. We can use   unlist()  to get a simple vector for our convenience.
unlist(lapply(all_prices4$june_price, power_function2, 4))

Now we are returned the fourth power of the june_price column as a vector.

Now we will again work with a combined array, which has the prices of different items in three different months each for 2017 and 2018. Do you remember the structure of it? It looked like this:

Here, the first matrix corresponds to prices for 2017 and the second matrix corresponds to 2018. We will now recreate this array to become a list of matrices in the following way:

combined2 = list(matrix(c(jan_2018, mar_2018, june_2018), nrow = 3), 
matrix(c(jan_2017, mar_2017, june_2017), nrow = 3))
combined2

This returns us the following list of matrices:

Now, if we want the prices for March for both 2017 and 2018, we can use lapply() in the following way:

lapply(combined2, "[", 2,)

So, what this has done is selected the second row from each list:

Now we can modify it further to select a column, row, or any element according to our needs.

lapply() can be used with data frames, lists, and vectors.