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

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. 
主站蜘蛛池模板: 全南县| 文化| 新丰县| 乡城县| 社旗县| 堆龙德庆县| 万州区| 海城市| 凤山县| 甘孜县| 阿拉善右旗| 饶平县| 辰溪县| 江口县| 满城县| 湟中县| 台北县| 千阳县| 九龙坡区| 麟游县| 桐梓县| 郁南县| 林口县| 亚东县| 万安县| 霍林郭勒市| 天气| 都匀市| 博爱县| 龙泉市| 许昌市| 兰坪| 哈巴河县| 峨眉山市| 胶州市| 法库县| 兴业县| 开鲁县| 兴安县| 桃园市| 方山县|