0
0
R Programmingprogramming~5 mins

Special operators (%in%, %*%) in R Programming

Choose your learning style9 modes available
Introduction

Special operators help you do common tasks easily, like checking if something is in a list or multiplying matrices.

When you want to check if values exist inside a group of values.
When you need to multiply two matrices together.
When filtering data based on membership in a set.
When performing mathematical operations on tables of numbers.
When working with data frames and you want to find matching elements.
Syntax
R Programming
x %in% y
x %*% y

%in% checks if elements of x are found in y and returns TRUE or FALSE.

%*% performs matrix multiplication between x and y.

Examples
Checks which numbers in the first list are also in the second list.
R Programming
c(1, 2, 3) %in% c(2, 3, 4)
Multiplies two 2x2 matrices together.
R Programming
matrix(c(1, 2, 3, 4), nrow=2) %*% matrix(c(5, 6, 7, 8), nrow=2)
Checks if the word "apple" is in the list of fruits.
R Programming
"apple" %in% c("banana", "apple", "cherry")
Sample Program

This program checks which numbers in values are also in check using %in%. Then it multiplies two matrices using %*% and prints both results.

R Programming
values <- c(10, 20, 30, 40)
check <- c(20, 50)
result_in <- values %in% check

mat1 <- matrix(c(1, 2, 3, 4), nrow=2)
mat2 <- matrix(c(5, 6, 7, 8), nrow=2)
result_mult <- mat1 %*% mat2

print(result_in)
print(result_mult)
OutputSuccess
Important Notes

%in% returns a logical vector showing TRUE or FALSE for each element.

%*% requires the number of columns in the first matrix to match the number of rows in the second matrix.

These operators make code easier to read and write for common tasks.

Summary

%in% checks membership of elements in a vector or list.

%*% performs matrix multiplication.

Both are special operators that simplify common operations in R.