variety =="Local_Check"# Is it the local check? FALSE
[1] FALSE
variety !="Local_Check"# Is it NOT the local check? TRUE
[1] TRUE
# On vectorsplot_yields <-c(5.2, 4.5, 6.1, 5.5)plot_yields >5.0# Which plots yielded above 5.0? [TRUE FALSE TRUE TRUE]
[1] TRUE FALSE TRUE TRUE
plot_varieties <-c("ICARDA_Gold", "Local_Check", "ICARDA_RustResist", "ICARDA_Gold")# Which plots are ICARDA_Gold? [TRUE FALSE FALSE TRUE]plot_varieties =="ICARDA_Gold"
[1] TRUE FALSE FALSE TRUE
# Combining conditions# Find plots where yield > 5.0 AND variety is ICARDA_Gold(plot_yields >5.0) & (plot_varieties =="ICARDA_Gold") # [TRUE FALSE FALSE TRUE]
[1] TRUE FALSE FALSE TRUE
# Find plots where yield > 6.0 OR variety is Local_Check(plot_yields >6.0) | (plot_varieties =="Local_Check") # [FALSE TRUE TRUE FALSE]
[1] FALSE TRUE TRUE FALSE
6.3 Vectorization: R’s Superpower
Many R operations are vectorized, meaning they automatically apply to each element of a vector without needing you to write a loop. This makes R code concise and efficient. We’ve already seen this with arithmetic (plot_yields + 0.5) and comparisons (plot_yields > 5.0).
Functions like mean(), sum(), min(), max(), sd() (standard deviation), length() also work naturally on vectors:
# Select rows where the variety is resistantresistant_plots <- trial_data[trial_data$Is_Resistant ==TRUE, ] # Or just trial_data[trial_data$Is_Resistant, ]print(resistant_plots)
The apply() family of functions lets us apply a function to the rows or columns in a matrix or data frame, a list or a vector.
# Imagine we have a data matrix of plot yield values for different varieties.# Each row represents a variety and each column a yield measurement for each trialplot_trials <-matrix(c(5.2, 4.5, 6.1, 5.5, 4, 6.6, 7, 5.1, 5.3), nrow =3, ncol =3)# We calculate the mean for each variety (each row)# 1 means function is run on rows, 2 would mean function is run on columnsapply(plot_trials, 1, mean)
[1] 5.900000 4.533333 6.000000
Exercise: Select the data for the ‘Local_Check’ variety from the trial_data data frame.