Class 7
Class 7
R Math
Simple Math
In R, you can use operators to perform common mathematical operations on
numbers.
Example
10 + 5
Try it Yourself »
Example
10 - 5
Try it Yourself »
You will learn more about available operators in our R Operators Tutorial.
For example, the min() and max() functions can be used to find the lowest or
highest number in a set:
Example
Try it Yourself »
sqrt()
The sqrt() function returns the square root of a number:
Example
sqrt(16)
Try it Yourself »
abs()
The abs() function returns the absolute (positive) value of a number:
Example
abs(-4.7)
Try it Yourself »
Example
Hanish statistics and training institute 8185815527
Hanish statistics and training institute 8185815527
ceiling(1.4)
floor(1.4)
Try it Yourself »
R Strings
String Literals
Strings are used for storing text.
Example
"hello"
'hello'
Try it Yourself »
Example
str <- "Hello"
str # print the value of str
Try it Yourself »
Multiline Strings
You can assign a multiline string to a variable like this:
Example
str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."
Try it Yourself »
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:
Example
str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."
cat(str)
Try it Yourself »
Escape Characters
To insert characters that are illegal in a string, you must use an escape
character.
Example
str <- "We are the so-called "Vikings", from the north."
str
Result:
Error: unexpected symbol in "str <- "We are the so-called "Vikings"
Try it Yourself »
Example
The escape character allows you to use double quotes when you normally would
not be allowed:
str <- "We are the so-called \"Vikings\", from the north."
str
cat(str)
Try it Yourself »
Hanish statistics and training institute 8185815527
Hanish statistics and training institute 8185815527