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

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.
主站蜘蛛池模板: 陈巴尔虎旗| 岳西县| 海淀区| 怀宁县| 武汉市| 佛冈县| 汝城县| 金堂县| 金川县| 孟村| 宁城县| 辽中县| 汉源县| 丹巴县| 阳谷县| 莆田市| 郴州市| 黄冈市| 西平县| 尤溪县| 女性| 梁河县| 临夏县| 凤山县| 江永县| 青州市| 南城县| 桐梓县| 聂荣县| 西乌珠穆沁旗| 宣城市| 兴隆县| 田阳县| 阳曲县| 北流市| 邢台县| 明光市| 泸水县| 阿鲁科尔沁旗| 时尚| 西昌市|