Function in-class exercise3
This exercise computes mean scores depending on type using different approaches. While the input and the output is in different forms, the advantages and disadvantages of each method will be explained below.
Method 1 computes mean scores depending on type by aggregate function. Aggregate is powerful because the syntax is easy and the output is readable as a dataframe.
Method 2 uses sapply function to compute the mean scores by spliting the data into lists and give output in matrix. The sapply is useable when input is a list and the desired output is a vector or a matrix.
## a b c u
## Tetrahydrocortisone 2.966667 8.18 19.72 14.01667
## Pregnanetriol 2.440000 1.12 5.50 1.20000
Method 3 creates a user-defined function with an agrument that subset the selected column and compute means scores by columns, return the value as lists, and combine the list by rows. The function() is powerful that we can define the function to complete a rountine, but in this case the syntax is much harder than aggregate.
do.call("rbind", as.list(
by(Cushings, list(Cushings$Type), function(x) {
y <- subset(x, select = -Type)
apply(y, 2, mean)
}
)))## Tetrahydrocortisone Pregnanetriol
## a 2.966667 2.44
## b 8.180000 1.12
## c 19.720000 5.50
## u 14.016667 1.20
Method 4 uses tidyR to group the data by type and summarize mean scores depending on type. TidyR uses verb(group_by and summarize) for statement which could be easier for beginner to understand, but in some cases it is not as neat and stable as base R.
Cushings %>%
group_by(Type) %>%
summarize( t_m = mean(Tetrahydrocortisone), p_m = mean(Pregnanetriol))Method 5 creates a list of data frames containing all the nested variables. It created three new variable but “avg” is not displayed in the result.
Cushings %>%
nest(-Type) %>%
mutate(avg = map(data, ~ apply(., 2, mean)),
res_1 = map_dbl(avg, "Tetrahydrocortisone"),
res_2 = map_dbl(avg, "Pregnanetriol")) ## Warning: All elements of `...` must be named.
## Did you want `data = c(Tetrahydrocortisone, Pregnanetriol)`?