
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minus Every Element of a Vector with Another Vector in R
To minus every element of a vector with every element of another vector, we can use outer function by defining the subtraction sign.
For example, if we have two vectors say x and y and we want to minus every element in x from every element in y then we can use the below mentioned command −
outer(x,y,`-`)
Example 1
Following snippet creates a sample vector −
x1<-rpois(10,5) y1<-rpois(10,8) outer(x1,y1,`-`)
The following vector is created −
[,1][,2][,3][,4][,5][,6][,7][,8][,9][,10] [1,] 1 -4 -3 -1 -4 -8 -4 -5 -1 0 [2,] 0 -5 -4 -2 -5 -9 -5 -6 -2 -1 [3,] -1 -6 -5 -3 -6 -10 -6 -7 -3 -2 [4,] 1 -4 -3 -1 -4 -8 -4 -5 -1 0 [5,] -2 -7 -6 -4 -7 -11 -7 -8 -4 -3 [6,] 1 -4 -3 -1 -4 -8 -4 -5 -1 0 [7,] 0 -5 -4 -2 -5 -9 -5 -6 -2 -1 [8,] -1 -6 -5 -3 -6 -10 -6 -7 -3 -2 [9,] 0 -5 -4 -2 -5 -9 -5 -6 -2 -1 [10,] 1 -4 -3 -1 -4 -8 -4 -5 -1 0
Example 2
Following snippet creates a sample vector −
x2<-rpois(10,10) y2<-rpois(10,2) outer(x2,y2,`-`)
The following vector is created −
[,1][,2][,3][,4][,5][,6][,7][,8][,9][,10] [1,] 6 9 9 7 7 7 7 7 5 7 [2,] 7 10 10 8 8 8 8 8 6 8 [3,] 7 10 10 8 8 8 8 8 6 8 [4,] 3 6 6 4 4 4 4 4 2 4 [5,] 10 13 13 11 11 11 11 11 9 11 [6,] 7 10 10 8 8 8 8 8 6 8 [7,] 9 12 12 10 10 10 10 10 8 10 [8,] 5 8 8 6 6 6 6 6 4 6 [9,] 9 12 12 10 10 10 10 10 8 10 [10,] 13 16 16 14 14 14 14 14 12 14
Example 3
Following snippet creates a sample vector −
x3<-rpois(10,1) y3<-rpois(10,2) outer(x3,y3,`-`)
The following vector is created −
[,1][,2][,3][,4][,5][,6][,7][,8][,9][,10] [1,] -4 0 -1 0 -1 0 -1 0 1 0 [2,] -5 -1 -2 -1 -2 -1 -2 -1 0 -1 [3,] -4 0 -1 0 -1 0 -1 0 1 0 [4,] -3 1 0 1 0 1 0 1 2 1 [5,] -3 1 0 1 0 1 0 1 2 1 [6,] -3 1 0 1 0 1 0 1 2 1 [7,] -3 1 0 1 0 1 0 1 2 1 [8,] -2 2 1 2 1 2 1 2 3 2 [9,] -4 0 -1 0 -1 0 -1 0 1 0 [10,] -4 0 -1 0 -1 0 -1 0 1 0
Example 4
Following snippet creates a sample vector −
x4<-rpois(10,5) y4<-rpois(5,2) outer(x4,y4,`-`)
The following vector is created −
[,1][,2][,3][,4][,5] [1,] -2 0 0 2 -3 [2,] 3 5 5 7 2 [3,] 0 2 2 4 -1 [4,] -1 1 1 3 -2 [5,] 3 5 5 7 2 [6,] -1 1 1 3 -2 [7,] -1 1 1 3 -2 [8,] 2 4 4 6 1 [9,] 3 5 5 7 2 [10,] -2 0 0 2 -3
Example 5
Following snippet creates a sample vector −
x5<-rpois(10,2) y5<-rpois(8,5) outer(x5,y5,`-`)
The following vector is created −
[,1][,2][,3][,4][,5][,6][,7][,8] [1,] -1 -2 0 -2 -1 -3 0 1 [2,] -5 -6 -4 -6 -5 -7 -4 -3 [3,] -3 -4 -2 -4 -3 -5 -2 -1 [4,] -5 -6 -4 -6 -5 -7 -4 -3 [5,] -3 -4 -2 -4 -3 -5 -2 -1 [6,] -4 -5 -3 -5 -4 -6 -3 -2 [7,] -1 -2 0 -2 -1 -3 0 1 [8,] -2 -3 -1 -3 -2 -4 -1 0 [9,] -5 -6 -4 -6 -5 -7 -4 -3 [10,] -2 -3 -1 -3 -2 -4 -1 0
Advertisements