Examples Of R Code: The Basic In R

Hi everyone, This article will share examples of R code and all the basics in R. So, if you are interested in this topic, follow the example below.

Comments are denoted by a ‘# ‘. R ignores code that begins with a # when running it.

Before each line of code in this example, a remark is used:

# This line is a comment
cat("Hello, learnshare IT.\n")

Output

Hello, learnshare IT.

Examples of R Variables

Data values are kept in variables as storage.

There needs to be a command in R for declaring variables. When a variable is initially given a value, it is considered to have been formed. Use the ‘<-‘ symbol to give a variable a value. Input the variable name to output (or print) the value:

# Create a name variable
str <- "I love LearnShare IT"

# View a result
str

Output

[1] "I love LearnShare IT"

Examples of R Numbers

R offers three different number types: numeric, integer, and complex.

When you give them a value, number-type variables are created:

x <- 2.8 # numeric
y <- 5L # integer
z <- 3i # complex

Examples of R Strings

Text is stored using strings.

Either single quotation marks or double quotation marks are used to enclose a string:

“IT” is equivalent to ‘IT’:

x <- "IT"
x1 <- "IT"

# View a result
x
x1

Output

[1] "IT"
[1] "IT"

Examples of R Operators

Operations on variables and values are carried out using operators.

See the example below

x <- 10
y <- 3

x + y # 13

# Subtract operator
x - y # 7

# Divide operator
x %/% y # 3

# Divide by the remainder operator
x %% y # 1

Output

[1] 13
[1] 7
[1] 3
[1] 1

Examples of R If…Else

Here, we will If…else to print the max number. Follow the code example below:

x <- 10
y <- 5

if (x < y) {
y
} else {
x
}

Output

[1] 10

Examples of R While Loop

Below is an example of While Loop basic in code in R to calculate the sum from 1 to 5.

i <- 1
res <- 0

while (i <= 5) {
res <- res + i
i <- i + 1
}

# View a result
res

Output

[1] 15

Examples of R For Loop

For iterating through a series, we also use a for loop to calculate the sum from 1 to 5 as follows

res <- 0

for (i in 1:5) {
res <- res + i
}

# View a result
res

Output

[1] 15

Examples of R Functions

A block of code known as a function only executes when invoked.

Data that you supply to a function are referred to as parameters.

A function may return data as a result. Check out the code example below

res <- 0

# Create a function
cal_sum <- function(n) {
for (i in 1:n) {
res <- res + i
}
return(res)
}

# View a result
cal_sum(5)

Output

[1] 15

Summary

In conclusion, we will learn about R code examples and hope you can code the basics in R after the examples above. So, if you have any questions, don’t hesitate to comment below. Thanks for reading!

Have a great day!

Posted in R