In R programming, vectorized operations
allow you to perform arithmetic or logical operations on entire vectors at
once, without having to loop through each element individually. This makes code
more efficient and easier to read.
Vectorized
operations in R allow
you to perform calculations on large datasets quickly and easily.
The syntax for vectorized operations is
very similar to regular arithmetic, logical, or comparison operations in R,
with the only difference being that you apply the operation to vectors rather
than individual values.
Example:
x
<- c(1, 2, 3)
y
<- c(2, 4, 6)
x
* y
Output:
[1]
2 8 18
In
this example, we multiply two vectors x and y element-wise, which returns a new
vector of the same length with the product of each pair of corresponding
elements.
Common
Vectorized Operations:
l Arithmetic
operations: +, -, *, /, ^
l Comparison
operations: ==, !=, <, >, <=, >=
l Logical
operations: &, |, !
l Mathematical
functions: sin(), cos(), sqrt(), log(), exp()
All
of these operations work on vectors in the same way as they do on scalars.
For
example, you can use the sin() function to calculate the
sine of each element in a vector:
x
<- c(0, pi/2, pi, 3*pi/2, 2*pi)
sin(x)
Output:
[1]
0.000000e+00 1.000000e+00 1.224647e-16 -1.000000e+00 -2.449294e-16
In this example, we create a vector x
containing five angles in radians, and then use the sin() function to calculate
the sine of each angle. The result is a new vector with the same length as x.
No comments:
Post a Comment