Scalar in R programming
A scalar is a single value that
represents a quantity or measurement. Scalars can be created by assigning a
value to a variable using the assignment operator, which is the
"<-" Or "=" Symbol.
Ø Types of scalars:
a. Numeric
scalar: A numeric scalar represents a numerical value,
such as an integer or a decimal. Syntax: X
<- 3.14
b. Logical
scalar: A logical scalar represents a boolean value that
is either true or false.
Syntax: Y <- true
c. Character
scalar: A character scalar represents a string of
characters, such as a word or a sentence.
Syntax: Z <- "Hello
world"
d. Complex
scalar: A complex scalar represents a complex number with
a real and imaginary component.
Syntax: W <- 2 + 3i
Ø Common
operations
a. Arithmetic
operations: Scalars can be used in arithmetic
operations such as addition, subtraction, multiplication, and division. The
arithmetic operators in r are +, -, *, and /.
For
example: 3 + 2
Output:
5
b. Comparison
operations: Scalars can be compared using
comparison operators such as less than, greater than, equal to, less than or
equal to, greater than or equal to, and not equal to. The comparison operators
in r are <, >, ==, <=, >=, and !=.
For
example: 3 < 5
Output:
True
c. Logical
operations: Scalars can also be combined using logical
operators such as and, or, and not. The logical operators in r are &, |. and !.
For
example: True & true
Output:
True
d. String
operations: Scalars of type character can be
manipulated using string operations such as concatenation, substring, and
length. The concatenation operator in r is paste(), the substring function is
substr(), and the length function is nchar().
For
example:
Paste("Hello",
"World") #
concatenation
Substr("Hello
world", 1, 5) #
substring
Nchar("Hello
world") #
length
Output:
"Hello world"
"Hello"
11