'R Assignment about loops and conditions
I have just started learning R and am having trouble solving this homework about loops and conditions. I am sorry to ask here, but I really did not know where to search for help, and the stackoverflow community is always so kind. I'd be grateful if anyone could help. Thank you!
ASSIGNMENT
Using the mtcars dataset and a for/while loop, create a vector containing the mean mpg by group of cars with the same amount of cylinders cyl(so that the vector stores the averag mpg for cars with 2 cylinders, for cars with 4 cylinders, etc.) of compute the mean mpg
Using the mtcars dataset and sapply, create a two-column matrix that stores in the first column the median wt by gear and in the second column the hp of the group (in the first row there is the median wt for cars with 3 gears, in the second row there is the median wt for cars with four gears, etc.)
Using the mtcars dataset and the function aggregate, compute the same information of points 1 and 2
Create a function named switching_fun that takes a vector as an input and:
If the input vector is a numeric, it returns the average
If the vector is a character, it returns the number of unique occurrences 3. If the vector is a factor, it returns its length Use apply to evaluate the function switching_fun on all the columns of the iris dataset
Create a function named switchinglist_fun that takes a vector as an input and:
If the input vector is a numeric, it returns the percentage of elements above the mean
If the vector is a character, it returns its unique elements 3 If the vector is a factor, it returns its levels (see the function(?levels) Use lapply to evaluate the function switching_fun on all the columns of the iris dataset (note that lapply allows to return output with different length)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
