- Hands-On Geospatial Analysis with R and QGIS
- Shammunul Islam
- 355字
- 2021-06-10 18:44:25
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:

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.
- Word 2000、Excel 2000、PowerPoint 2000上機指導與練習
- 我的J2EE成功之路
- Practical Ansible 2
- 會聲會影X5視頻剪輯高手速成
- 機器學習與大數據技術
- 群體智能與數據挖掘
- 可編程序控制器應用實訓(三菱機型)
- Dreamweaver CS6精彩網頁制作與網站建設
- 教育機器人的風口:全球發展現狀及趨勢
- Unity Multiplayer Games
- Bayesian Analysis with Python
- Visual Studio 2010 (C#) Windows數據庫項目開發
- Artificial Intelligence By Example
- SQL Server數據庫應用基礎(第2版)
- IBM? SmartCloud? Essentials