0% found this document useful (0 votes)
50 views21 pages

Learn R in W3 School

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views21 pages

Learn R in W3 School

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

# Learn R in W3 school _

https://www.w3schools.com/r/r_exercises.asp

1. R syntax

1.1 print function

print("Hello World!")

1.2 For Loops, print() function is necessary e.g

for (x in 1:10) {print(x)}

Meaning x includes 1-10, print (x)


2. R comments

Comments starts with a #

# to print

print ("Hello World!")


3. R variables

3.1 Creating Variables in R

“<-” or “=” meaning “is”.

name <- "Ramesh"

age <- 31

name

age

# output "Ramesh"

# output 40

Note: [Name and age are variables, Ramesh and 31 are values. After
assigning variables and values, just type variables (name and age),
and run. Output will be given as Ramesh, 31]

The sign “<-” is called assignment operator. Or equal to “=” sign can
be used.

Print / Output Variables

name <- "John Doe"

name # auto-print the value of the name variable

or,
name <- "John Doe"

print(name) # print the value of the name variable

3.2 R Concatenate Elements (join)

Use “paste()” function

Eg. 1

text <- "genius"


paste("Ramesh is", text)

#output (“Ramesh is genius”)

Eg. 2

text2 <- "is intelligent"

text1 <- "Ramesh"

paste (text1, text2)

# output (“Ramesh is intelligent”)

Eg. 3 (for numbers)

num1 <- 5
num2 <- 10
num1 + num2

# output (15)
Eg. 4 (num + text can’t operate)

num <- 5
text <- "Some text"
num + text

#output: error

Eg. 4 (num + text can’t operate, but with paste() function can be
joined)

num <- 5
text <- "Some text"
paste (num + text)

#output: “5 some text”

3.3 Multiple Variables

# Assign the same value to multiple variables in one line

var1 <- var2 <- var3 <- "Ramesh is out of this world"

# Print variable values

var1

var2

var3

#output:

"Ramesh is out of this world"


"Ramesh is out of this world"

"Ramesh is out of this world"

3.4 R Variable Names (Identifiers)

Variable Names (Rules to follow while assigning variable name)

A variable can have a short name (like x and y) or a more descriptive


name (age, carname, total_volume). Rules for R variables are:

 A variable name must start with a letter and can be a combination


of letters, digits, period(.)
and underscore(_). If it starts with period(.), it cannot be
followed by a digit.

 A variable name cannot start with a number or underscore (_)

 Variable names are case-sensitive (age, Age and AGE are three
different variables)

 Reserved words cannot be used as variables (TRUE, FALSE, NULL,


if...)

# Legal variable names:


myvar <- "John"
my_var <- "John"
myVar <- "John"
MYVAR <- "John"
myvar2 <- "John"
.myvar <- "John"

# Illegal variable names:


2myvar <- "John"
my-var <- "John"
my var <- "John"
_my_var <- "John"
my_v@ar <- "John"
TRUE <- "John"
4. R Data Types

In programming, data type is an important concept.


Variables can store data of different types, and different types can
do different things.
In R, variables do not need to be declared with any particular type,
and can even change type after they have been set:
Eg.1
my_var <- 30 # my_var is type of numeric
my_var <- "Sally" # my_var is now of type character (aka string)

Basic Data Types


Basic data types in R can be divided into the following types:
 numeric - (10.5, 55, 787)
 integer - (1L, 55L, 100L, where the letter "L" declares this as
an integer)
 complex - (9 + 3i, where "i" is the imaginary part)
 character (a.k.a. string) - ("k", "R is exciting", "FALSE",
"11.5")
 logical (a.k.a. boolean) - (TRUE or FALSE)
We can use the class() function to check the data type of a variable:

# numeric
x <- 10.5
class(x)

# integer (letter “L” must be used)


x <- 1000L
class(x)

# complex (letter “i” must be used)


x <- 9i + 3
class(x)
# character/string
x <- "R is exciting"
class(x)

# logical
x <- TRUE
class(x)
5. R Numbers

x <- 10.5 # numeric


y <- 10L # integer
z <- 1i # complex

Eg. 1

x <- 10.5
y <- 55

# Print values of x and y


x
y

# Print the class name of x and y


class(x)
class(y)

Eg. 2

x <- 1L # integer
y <- 2 # numeric

# convert from integer to numeric:


a <- as.numeric(x)

# convert from numeric to integer:


b <- as.integer(y)

# print values of x and y


x
y

# print the class name of a and b


class(a)
class(b)
6. R math

6.1 Simple math


10+5
10-5
10*5
10/5

6.2 Built-in Math Functions

max(5, 10, 15)

min(5, 10, 15)

sqrt(16)

abs (-1465) # absolute positive

ceiling () and floor()

#The ceiling() function rounds a number upwards to its nearest


integer, and the floor() function rounds a number downwards to
its nearest integer, and returns the result:

ceiling(1.4) #output: 2 (upward to its nearest integer)

floor(1.4) #output: 1 (downward to its nearest integer)


7. R strings

7.1 String literals

Strings, surrounded by either single quotation marks, or


double quotation marks, are used for storing text.

Eg. “Hello” or ‘Hello’

7.2 Assign a String to a Variable

Eg.
str <- "Hello"
str # print the value of str

7.3 Multiline Strings

Eg.

str <- "Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."

str # print the value of str

However, note that R will add a "\n" at the end of each


line break. This is called an escape character, and
the n character indicates a new line.
If you want the line breaks to be inserted at the same
position as in the code, use the cat() function:

str <- "Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."

cat(str)

7.4 string length


There are many usesful string functions in R.
For example, to find the number of characters in a string,
use the nchar() function:

Eg.
str <- "Hello World!"

nchar(str)

#output : 12

Eg.
str <- "Ramesh is exceptionally productive man"
nchar (str)

#output : 38

7.5 Check a String

Use the grepl() function to check if a character or a


sequence of characters are present in a string:

Eg.

str <- "Hello World!"

grepl("H", str)
grepl("Hello", str)
grepl("X", str)

#Output: [1] TRUE, meaning “character H is present in the


string”
#Output: [1] TRUE
#Output: [1] FALSE

7.6 Combine Two Strings

Use the paste() function to merge/concatenate two strings:


Eg.
str1 <- "Ramesh is exceptionally"
str2 <- "prepared and productive person"

paste(str1, str2)

#output: [1] "Ramesh is exceptionally prepared and


productive person"
8. R Escape Characters

Escape Characters

To insert characters that are illegal in a string, you must


use an escape character.
An escape character is a backslash \ followed by the character
you want to insert.
An example of an illegal character is a double quote inside a
string that is surrounded by double quotes:

Eg.
str <- "We are the so-called "Vikings", from the north."

str

#output: Error: unexpected symbol in "str <- "We are the so-
called "Vikings"

To fix this problem, use the escape character \":

Eg.
str <- "Ramesh is \"exceptionally\" productive guy"

str
cat(str)

#output: [1] "Ramesh is \"exceptionally\" productive guy"


Ramesh is "exceptionally" productive guy

Other escape characters in R:

Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
9. R Booleans (Logical Values)

Eg. 1
10 > 9 # TRUE because 10 is greater than 9
10 == 9 # FALSE because 10 is not equal to 9
10 < 9 # FALSE because 10 is greater than 9

EG. 2
You can compare variables as well.

a <- 10
b <- 9

a > b #output: TRUE

EG. 3
a<-1000
b<-1

a-b == 999 #output: TRUE

EG. 4

(use of If)

a <- 200
b <- 33

if (b > a) { print ("b is greater than a") } else { print("b


is not greater than a")}

#output: [1] "b is not greater than a"

EG. 5

a <- 33
b <- 33

if (b > a) { print ("b is greater than a") }


if (a>b) { print("b is not greater than a")}

if (a==b) { print("a is equals to b")}

#output: [1] "a is equals to b"


10. R operators

Operators are used to perform operations on variables and


values.

R divides the operators in the following groups:


a. R Arithmetic Operators
b. Assignment operators
c. Comparison operators
d. Logical operators
e. Miscellaneous operators

EG. 1

11 + 5

a. R Arithmetic Operators

Operato Name Example


r
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
^ Exponent x^y
%% Modulus (Remainder from x %% y
division)
%/% Integer Division x%/%y

b. Assignment operators
Assignment operators are used to assign values to
variables:

my_var <- 3
my_var <<- 3 (note: <<- is a global assigner.)
3 -> my_var
3 ->> my_var
my_var # print my_var #output: 3

It is also possible to turn the direction of the


assignment operator.
x <- 3 is equal to 3 -> x
c. Comparison operators
Comparison operators are used to compare two

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or x >= y
equal to
<= Less than or x <= y
equal to
values:

d. Logical operators
Logical operators are used to combine conditional
statements:

Operator Description
& Element-wise Logical AND operator. It returns TRUE if both elements are TRUE
&& Logical AND operator - Returns TRUE if both statements are TRUE
| Elementwise- Logical OR operator. It returns TRUE if one of the statement is TRUE
|| Logical OR operator. It returns TRUE if one of the statement is TRUE.
! Logical NOT - returns FALSE if statement is TRUE

e. Miscellaneous operators
Miscellaneous operators are used to manipulate
data:

Operator Description Example


: Creates a series of numbers in a x <- 1:10
sequence
%in% Find out if an element belongs to a
vector x %in% y
%*% Matrix Multiplication x <- Matrix1 %*%
Matrix2
11. R If….Else

11.1 Conditions and If Statements


R supports the usual logical conditions from mathematics:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or x >= y
equal to
<= Less than or x <= y
equal to

These conditions can be used in several ways, most commonly in "if


statements" and loops.

You might also like