Task: Introduction to R
Find the solution here after the session ends.
Getting started
Copy and paste the following three vectors into your R script:
species: name of the speciesbodywt_kg: body weight in kgbrainwt_kg: brain weight in kg
species <- c(
"MountainBeaver", "Cow", "GreyWolf", "Goat",
"GuineaPig", "Diplodocus", "AsianElephant", "Donkey",
"Horse", "PotarMonkey", "Cat", "Giraffe",
"Gorilla", "Human", "AfricanElephant", "Triceratops",
"RhesusMonkey", "Kangaroo", "GoldenHamster", "Mouse",
"Rabbit", "Sheep", "Jaguar", "Chimpanzee",
"Rat", "Brachiosaurus", "Mole", "Pig"
)
bodywt_kg <- c(
1.4, 465, 36.3, 27.7, 1., 11700, 2547, 187.1,
521, 10, 3.3, 529, 207, 62, 6654, 9400,
6.8, 35, 0.1, 0.02, 2.5, 55.5, 100, 52.2,
0.3, 87000, 0.1, 192
)
brainwt_kg <- c(
0.0081, 0.423, 0.1195, 0.115, 0.0055, 0.05,
4.603, 0.419, 0.655, 0.115, 0.0256, 0.68,
0.406, 1.32, 5.712, 0.07, 0.179, 0.056,
0.001, 0.0004, 0.0121, 0.175, NA, 0.44,
0.0019, 0.1545, NA, 0.18
)Variables and vectors
- What is the 13th species in the vector?
- Get the species at positions 6, 13, and 14.
- How many species are in the dataset? Save the number in a variable called
n_species.- Hint: try the function
length()
- Hint: try the function
Vector arithmetic
- Calculate the brain-to-body weight ratio for all species and save it in a new variable called
ratio. - Convert the body weight from kg to grams and save it in a variable called
bodywt_g.
Functions and missing values
- Calculate the mean body weight and the mean brain weight. What happens for brain weight and how do you fix it?
- Hint: check
?mean
- Hint: check
- Also try
sum()andmedian()on brain weight.
Optional tasks (if you finish early)
You can do these in any order — or skip them and just take a break.
- Use the
round()function to round theratiovector to 2 decimal places.- Use
?roundto find out which argument controls the number of decimal places.
- Use
- Try
min(),max(),sum(), andsd()onbrainwt_kg. Do they all need the same fix for missing values? - Use
sum()together withis.na()to find out how many missing values are inbrainwt_kg.- Hint:
is.na()returnsTRUEfor eachNAvalue. What happens if yousum()a logical vector?
- Hint: