Hello, World! The following is a
"Hello, World!" program: > print("Hello, World!") [1] "Hello, World!"Here is an alternative version, which uses the cat() function: > cat("Hello, World!") Hello, World!
Basic syntax The following examples illustrate the basic
syntax of the language and use of the command-line interface. In R, the generally preferred
assignment operator is an arrow made from two characters , although = can be used in some cases. > x y y # Print the vector’s contents. [1] 1 4 9 16 25 36 > z z # Return the contents of z to the current environment. [1] 2 6 12 20 30 42 > z_matrix z_matrix [,1] [,2] [1,] 2 20 [2,] 6 30 [3,] 12 42 > 2 * t(z_matrix) - 2 # Transpose the matrix; multiply every element by 2; # subtract 2 from each element in the matrix; and # then return the results to the terminal. [,1] [,2] [,3] [1,] 2 10 22 [2,] 38 58 82 • Create a new dataframe object that contains the data from a transposed • z_matrix, with row names 'A' and 'B' > new_df names(new_df) new_df # Print the current results. X Y Z A 2 6 12 B 20 30 42 > new_df$Z # Output the Z column [1] 12 42 > new_df$Z == new_df['Z'] && new_df[3] == new_df$Z # The dataframe column Z can be accessed using the syntax $Z, ['Z'], or [3], and the values are the same. [1] TRUE > attributes(new_df) # Print information about attributes of the new_df dataframe $names [1] "X" "Y" "Z" $row.names [1] "A" "B" $class [1] "data.frame" > attributes(new_df)$row.names new_df X Y Z one 2 6 12 two 20 30 42
Structure of a function R can create
functions that add new functionality and enable code reuse.
Objects created within the body of the function (which are enclosed by curly brackets) remain
accessible only from within the function, and any
data type may be returned. In R, almost all functions and all
user-defined functions are
closures. The following is an example of creating a function to perform an arithmetic calculation: • The function's input parameters are x and y. • The function, named f, returns a linear combination of x and y. f The following is some output from using the function defined above: > f(1, 2) # 3 * 1 + 4 * 2 = 3 + 8 [1] 11 > f(c(1, 2, 3), c(5, 3, 4)) # Element-wise calculation [1] 23 18 25 > f(1:3, 4) # Equivalent to f(c(1, 2, 3), c(4, 4, 4)) [1] 19 22 25 It is possible to define functions to be used as
infix operators by using the special syntax `%name%`, where "name" is the function variable name: > `%sumx2y2%` 1:3 %sumx2y2% -(1:3) [1] 2 8 18 Since R version 4.1.0, functions can be written in a short notation (inspired by the
lambda calculus), which is useful for passing anonymous functions to higher-order functions: > sapply(1:5, \(i) i^2) # here \(i) is the same as function(i) [1] 1 4 9 16 25
Native pipe operator In R version 4.1.0, a native
pipe operator, |>, was introduced. This operator allows users to chain functions together, rather than using nested function calls. > nrow(subset(mtcars, cyl == 4)) # Nested without the pipe character [1] 11 > mtcars |> subset(cyl == 4) |> nrow() # Using the pipe character [1] 11 An alternative to nested functions is the use of intermediate objects, rather than the pipe operator: > mtcars_subset_rows num_mtcars_subset print(num_mtcars_subset) [1] 11 While the pipe operator can produce code that is easier to read, influential R programmers like
Hadley Wickham suggest to chain together at most 10-15 lines of code using this operator and saving them into objects having meaningful names to avoid
code obfuscation.
Object-oriented programming The R language has native support for
object-oriented programming. There are two native
frameworks, the so-called S3 and S4 systems. The former, being more informal, supports single dispatch on the first argument, and objects are assigned to a class simply by setting a "class" attribute in each object. The latter is a system like the
Common Lisp Object System (CLOS), with formal classes (also derived from
S) and generic methods, which supports
multiple dispatch and
multiple inheritance In the example below, summary() is a
generic function that dispatches to different methods depending on whether its
argument is a numeric
vector or a
factor: > data summary(data) Length Class Mode 5 character character > summary(as.factor(data)) a b c NA's 2 1 1 1
Modeling and plotting The R language has built-in support for
data modeling and graphics. The following example shows how R can generate and plot a
linear model with residuals. • Create x and y values x The output from the summary() function in the preceding code block is as follows: Residuals: 1 2 3 4 5 6 7 8 9 10 3.3333 -0.6667 -2.6667 -2.6667 -0.6667 3.3333 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -9.3333 2.8441 -3.282 0.030453 * x 7.0000 0.7303 9.585 0.000662 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 3.055 on 4 degrees of freedom Multiple R-squared: 0.9583, Adjusted R-squared: 0.9478 F-statistic: 91.88 on 1 and 4 DF, p-value: 0.000662
Mandelbrot set This example of a
Mandelbrot set highlights the use of
complex numbers. It models the first 20
iterations of the
equation z = z2 + c, where c represents different
complex constants. To run this sample code, it is necessary to first install the package that provides the write.gif() function: install.packages("caTools") The sample code is as follows: library(caTools) jet.colors == Version names ==