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

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. 
主站蜘蛛池模板: 湛江市| 中江县| 汤阴县| 麻城市| 农安县| 汉沽区| 随州市| 天津市| 丹阳市| 西乡县| 阿鲁科尔沁旗| 屯昌县| 乐清市| 莆田市| 南华县| 安溪县| 绩溪县| 河南省| 图木舒克市| 洞口县| 嘉鱼县| 东明县| 和龙市| 封丘县| 汾西县| 常山县| 彭水| 体育| 普陀区| 且末县| 遂宁市| 景德镇市| 偃师市| 疏勒县| 武平县| 翼城县| 栖霞市| 鸡泽县| 永兴县| 社会| 崇义县|