Content
Summary
R is a free, open-source statistical computing environment where users enter commands at a prompt, typically using GUIs like RStudio. Data is managed through objects and vectors, with arithmetic and statistical operations performed element-wise or via specific functions like mean() and sd().
Intuition
Think of R as a sophisticated calculator that remembers your work. You type instructions at a prompt, and R executes them immediately. Unlike simple calculators, R stores your results in 'objects' (like vectors) which you can manipulate later. A key feature is that operations like addition or square roots happen 'element-wise,' meaning they apply to every number in a list simultaneously. This makes R powerful for handling datasets, but you must remember that functions like var() calculate sample variance by default, and standard procedures may not work for complex tasks like meta-analysis without specific packages.
Key equations
Assignment operator creating a vector named x.
Function to compute the arithmetic average of vector x.
Function to compute the standard deviation, assuming sample data.
Function to compute an average where each value has a specific importance.
Derivation
- R operates by executing commands entered at the prompt (symbol >).
- Users create objects using the assignment operator <- or =.
- Vectors are created using c() and support element-wise arithmetic.
- Statistical summaries are generated using built-in functions like mean(), var(), and sd().
- Data import requires handling headers and missing values (NA) correctly.
Worked example
Calculate the weighted mean price for a portfolio with 200 shares at USD 78, 300 shares at USD 122, and 500 shares at USD 131.
- Define the price vector: price <- c(78, 122, 131)
- Define the weight vector (shares): shares <- c(200, 300, 500)
- Execute: weighted.mean(price, shares)
Answer 117.7
Common mistakes
- Assuming var() calculates population variance; it calculates sample variance by default.
- Plotting variables without specifying the dataset (e.g., plot(cylinders, mpg) instead of plot(
Auto$cylinders,Auto$mpg)). - Ignoring the header argument in read.table(), causing variable names to be treated as data.
- Applying standard R procedures to meta-analysis data, which yields incorrect p-values due to differing degrees of freedom rules.