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

apply

apply works on arrays or matrices and gives us an easier way to compute something row-wise or column-wise. For the apply() function, this row- or column-wise consideration is denoted by a margin. The apply() function takes the following form: apply(data, margin, function). This data has to be an array or a matrix, and the margin can be either 1 or 2, where 1 stands for a row-wise operation and 2 stands for a column-wise operation. We will work with the matrix all_prices, which has the following structure:

Here, we have a record of prices of three different items in three different months (January, March, and June), where a row represents the prices of an item in three different months and a column represents the prices of three different items in any single month. Now, if we want to know which item's price fluctuated most over these three months, we would have to compute a standard deviation row-wise for each row. We can do this very easily using margin = 1 in apply().

apply(all_prices, 1, sd)

We can see the standard deviation for these three items as follows:

Now suppose we want to know the month-wise total cost of all three items. As every column corresponds to different months, we can apply apply() with margin = 2 and a function mean to achieve this:

apply(all_prices, 2, sum)

This gives the sum for all three months in a vector:

We see that the total prices were the highest in June (the third column), totaling 78.

Note that the function that we use inside   apply() has to be without (). We just need to write its name without parentheses. 
主站蜘蛛池模板: 沭阳县| 湘乡市| 安乡县| 文水县| 乐陵市| 南乐县| 灵台县| 乌拉特前旗| 西充县| 贺兰县| 葵青区| 新源县| 大石桥市| 广饶县| 黄石市| 宁阳县| 望江县| 桐乡市| 石狮市| 忻城县| 延津县| 方山县| 阿克苏市| 曲水县| 五大连池市| 鄂伦春自治旗| 锡林浩特市| 大港区| 彭泽县| 靖西县| 陵川县| 万源市| 松原市| 仙桃市| 尤溪县| 河源市| 涞水县| 东平县| 武山县| 东丰县| 明水县|