![]() Note that as there were no food sold in the Store 4, the corresponding cell returns a NA value. Tapply(price, list(type, store), mean) Store 1 Store 2 Store 3 Store 4 In this example, we are going to apply the tapply function to the type and store factors to calculate the mean price of the objects by type and store. You can apply the tapply function to multiple columns (or factor variables) passing them through the list function. In this case, you can access the output elements with the $ sign and the element name. Mean_prices_list <- tapply(price, type, mean, simplify = FALSE) However, you can modify the output class to list if you set the simplify argument to FALSE. Hence, if needed, you can access each element of the output specifying the desired index in square brackets. It also should be noticed that the default output is of class “array”. You can verify it with the length function. ![]() Note that the tapply arguments must have the same length. ![]() Labels = c("toy", "food", "electronics", "drinks"))įinally, you can use the tapply function to calculate the mean by type of object of the stores as follows: # Mean price by product type Second, store the values as variables and convert the column named type to factor. Type = sample(1:4, size = 25, replace = TRUE), First, consider the following example dataset, that represents the price of some objects, its type and the store where they were sold. The tapply function is very easy to use in R.
0 Comments
Leave a Reply. |