scores is a data frame with 40 rows and 3 columns named student, section and total, where total is numeric and contains no missing values. A student writes two lines intending to keep only the rows where total exceeds 70. At least one of the rows numbered 4 through 40 has a total greater than 70.
a <- scores[scores$total > 70, ] b <- scores[scores$total > 70]
What is the difference between them?
a keeps the matching rows and all columns, while b's single index selects columns rather than rows and raises an undefined-columns error.
Both lines select the same rows, but b drops the data frame class and returns the values as a plain vector, so the difference is only in the type of object returned.
They produce the same result. The comma is optional whitespace inside the brackets, and R ignores it when only one index is supplied.
b is the current recommended form and a is older syntax kept only for backward compatibility, so both work but b should be preferred in new code.
Unlock full course notes by signing up
R and RStudio: difficulty 4
A colleague sends you the following script, which runs correctly on their laptop.
1 setwd("/Users/jdavies/Desktop/final analysis 2") 2 plots <- read.csv("plots.csv") 3 plots$height <- as.numeric(gsub(" cm", "", plots$height_cm)) 4 fit <- lmer(height ~ treatment + (1 | block), data = plots) 5 subset_rows <- plots[sample(nrow(plots), 20), ] 6 boxplot(height ~ treatment, data = subset_rows)
Answer all three parts.