- 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.
- 西門子S7-200 SMART PLC實(shí)例指導(dǎo)學(xué)與用
- 網(wǎng)絡(luò)化分布式系統(tǒng)預(yù)測(cè)控制
- 聊天機(jī)器人:入門、進(jìn)階與實(shí)戰(zhàn)
- Excel 2007常見技法與行業(yè)應(yīng)用實(shí)例精講
- Photoshop行業(yè)應(yīng)用基礎(chǔ)
- Linux嵌入式系統(tǒng)開發(fā)
- JRuby語(yǔ)言實(shí)戰(zhàn)技術(shù)
- 基于人工免疫原理的檢測(cè)系統(tǒng)模型及其應(yīng)用
- EDA技術(shù)及其創(chuàng)新實(shí)踐(Verilog HDL版)
- 細(xì)節(jié)決定交互設(shè)計(jì)的成敗
- 深度學(xué)習(xí)實(shí)戰(zhàn)
- Building Smart Drones with ESP8266 and Arduino
- 三維動(dòng)畫制作(3ds max7.0)
- 巧學(xué)活用WPS
- 博弈論與無線傳感器網(wǎng)絡(luò)安全