Learn R in W3 School
Learn R in W3 School
https://www.w3schools.com/r/r_exercises.asp
1. R syntax
print("Hello World!")
# to print
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.
or,
name <- "John Doe"
Eg. 1
Eg. 2
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)
var1 <- var2 <- var3 <- "Ramesh is out of this world"
var1
var2
var3
#output:
Variable names are case-sensitive (age, Age and AGE are three
different variables)
# numeric
x <- 10.5
class(x)
# logical
x <- TRUE
class(x)
5. R Numbers
Eg. 1
x <- 10.5
y <- 55
Eg. 2
x <- 1L # integer
y <- 2 # numeric
sqrt(16)
Eg.
str <- "Hello"
str # print the value of str
Eg.
cat(str)
Eg.
str <- "Hello World!"
nchar(str)
#output : 12
Eg.
str <- "Ramesh is exceptionally productive man"
nchar (str)
#output : 38
Eg.
grepl("H", str)
grepl("Hello", str)
grepl("X", str)
paste(str1, str2)
Escape Characters
Eg.
str <- "We are the so-called "Vikings", from the north."
str
#output: Error: unexpected symbol in "str <- "We are the so-
called "Vikings"
Eg.
str <- "Ramesh is \"exceptionally\" productive guy"
str
cat(str)
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
EG. 3
a<-1000
b<-1
EG. 4
(use of If)
a <- 200
b <- 33
EG. 5
a <- 33
b <- 33
EG. 1
11 + 5
a. R Arithmetic Operators
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
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: