Basic R Syntax and Commands

Basic R Syntax and Commands

R is a powerful programming language and environment used for statistical computing and graphics. In this section, we will cover the fundamental syntax and commands in R that will help you get started with your data analysis tasks in RStudio.

1. R as a Calculator

R can be used as a calculator for basic arithmetic operations. Here are some examples:

`R

Addition

3 + 5

returns 8

Subtraction

10 - 4

returns 6

Multiplication

6 * 7

returns 42

Division

20 / 4

returns 5

Exponentiation

2 ^ 3

returns 8

`

2. Assigning Values to Variables

In R, you can store values in variables using the assignment operator <-. Here’s how:

`R

Assigning a value to a variable

my_number <- 10 my_string <- "Hello, R!" `

You can then use these variables in calculations or functions:

`R

Using the variable

result <- my_number + 5

result will be 15

print(my_string)

prints 'Hello, R!'

`

3. Data Types in R

R has several data types, including: - Numeric: Numbers (e.g., 5, 3.14) - Character: Text strings (e.g., "Hello") - Logical: Boolean values (TRUE, FALSE)

You can check the type of a variable using the class() function:

`R

Checking data types

class(my_number)

returns 'numeric'

class(my_string)

returns 'character'

`

4. Basic Functions

R has many built-in functions you can use. Here are a few common ones: - sum(): Returns the sum of a numeric vector. - mean(): Returns the average of a numeric vector. - length(): Returns the number of elements in an object.

Example:

`R

Using basic functions

numbers <- c(10, 20, 30)

Calculating sum

sum_result <- sum(numbers)

returns 60

Calculating mean

mean_result <- mean(numbers)

returns 20

Length of vector

length_result <- length(numbers)

returns 3

`

5. Commenting Code

Comments are crucial for explaining code. In R, you can add comments using the # symbol:

`R

This is a comment

x <- 5

Assign 5 to x

`

Comments help others (and yourself) understand your code later.

6. Running Code in RStudio

To run your code in RStudio: - Type your code in the script editor. - Highlight the code and click on the 'Run' button or press Ctrl + Enter (Windows) / Cmd + Enter (Mac).

Conclusion

Understanding the basic syntax and commands in R is essential for performing data analysis. This knowledge will serve as the foundation for more advanced R programming techniques.

Practical Example

Let’s say you want to calculate the average of a series of test scores:

`R

Test scores vector

scores <- c(85, 90, 78, 92, 88)

Calculate average

average_score <- mean(scores) print(average_score)

prints the average score

`

This example demonstrates variable assignment, vector creation, and using the mean() function.

Back to Course View Full Topic