# Load in the dataset women
data("women")
Working with code
When we write our code it is useful to write descriptions about what each line is doing. This is an important step if you send your code to someone else and you want them to know what you have done, or if you don’t look at your code for a while and forget what you did!
We can add comments to our R script using the #
symbol.
Anything written after the #
symbol will not be evaluated by R as code. This means we can comment out lines of code.
# 2 + 2
3 + 4
[1] 7
Let’s go through one of our previous examples and add comments to our code.
# Load in the dataset women
data("women")
# Find the mean weight
<- mean(women$weight)
mean_weight
# Find which women had a weight more than the mean
<- which(women$weight > mean_weight)
which_rows
# Find corresponding weight and height for these rows
women[which_rows, ]
height weight
9 66 139
10 67 142
11 68 146
12 69 150
13 70 154
14 71 159
15 72 164
Debugging code
So far you may have had some errors and warnings when you run your R code. Learning how to fix R code, either written by yourself or someone else, takes time. Practice and understanding errors will help you get quicker - but even advanced R users still make mistakes.
Let’s look at some examples of errors in broken code and see if we can fix them.
<- c(100, 120, 90, 150, 110, ) heights
Error in c(100, 120, 90, 150, 110, ): argument 6 is empty
The mistake here is that we have a comma “,” after 110 but no number, so R is telling is that the argument is empty. If we delete the comma, then we do not get an error:
<- c(100, 120, 90, 150, 110) heights
Now that we have fixed the code, let’s try and plot our vector of heights.
<- c(100, 120, 90, 150, 110)
heights
hist(heights, xlab = "heights (cm)", xlab = "frequency")
Error in hist.default(heights, xlab = "heights (cm)", xlab = "frequency"): formal argument "xlab" matched by multiple actual arguments
Here we have accidentally used the argument xlab
twice and R has recognised this. Let’s change the second xlab
to ylab
.
<- c(100, 120, 90, 150, 110)
heights
hist(heights, xlab = "Height (in)", ylab = "frequency")
Now our code runs without errors.
Can you fix the following code so that its runs without errors?
# Load in data set chicken weights
data("chickwts")
# What column names of the data set
colname(chickwt)
Error in colname(chickwt): could not find function "colname"
# Make a box plot of the weight against feed
boxplot(weight ~ fed, data = chickwts)
Error in eval(predvars, data, env): object 'fed' not found
- The data set name was incorrect in
colnames
- Use ‘colnames’ not ‘colname’
- The column name is ‘feed’ not ‘fed’
# Load in data set chicken weights
data("chickwts")
# What column names of the data set
colnames(chickwts)
[1] "weight" "feed"
# Make a box plot of the weight against feed
boxplot(weight ~ feed, data = chickwts)