Primary
R Syntax ○|Definition|1st|20260204112247-00-⌔
R (programming language) - Wikipedia#Basic_syntax
Basic syntax
The following examples illustrate the basic syntax of the language and use of the command-line interface.1
In R, the generally preferred assignment operator is an arrow made from two characters
<-, although=can be used in some cases.2> x <- 1:6 # Create a numeric vector in the current environment > y <- x^2 # Similarly, create a vector based on the values in x. > y # Print the vector’s contents. [1] 1 4 9 16 25 36 > z <- x + y # Create a new vector that is the sum of x and y > z # Return the contents of z to the current environment. [1] 2 6 12 20 30 42 > z_matrix <- matrix(z, nrow = 3) # Create a new matrix that transforms the # vector z into a 3x2 matrix object > 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 <- data.frame(t(z_matrix), row.names = c("A", "B")) > names(new_df) <- c("X", "Y", "Z") # Set the column names of the new_df dataframe as X, Y, and Z. > 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 <- c("one", "two") # Access and then change the row.names attribute; this can also be done using the rownames() function > new_df X Y Z one 2 6 12 two 20 30 42Printed 2026-06-28.
(echo:: @ ᯤ)
Link to original Footnotes
Secondary
• • •