R outer()函数

outer()

直观来说是一个将x中每一个元素与y进行计算
例如,利用paste可以将xy元素相组合

> month.abb
 [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
> 1999:2003
[1] 1999 2000 2001 2002 2003
> outer(month.abb, 1999:2003, FUN = "paste")
      [,1]       [,2]       [,3]       [,4]       [,5]      
 [1,] "Jan 1999" "Jan 2000" "Jan 2001" "Jan 2002" "Jan 2003"
 [2,] "Feb 1999" "Feb 2000" "Feb 2001" "Feb 2002" "Feb 2003"
 [3,] "Mar 1999" "Mar 2000" "Mar 2001" "Mar 2002" "Mar 2003"
 [4,] "Apr 1999" "Apr 2000" "Apr 2001" "Apr 2002" "Apr 2003"
 [5,] "May 1999" "May 2000" "May 2001" "May 2002" "May 2003"
 [6,] "Jun 1999" "Jun 2000" "Jun 2001" "Jun 2002" "Jun 2003"
 [7,] "Jul 1999" "Jul 2000" "Jul 2001" "Jul 2002" "Jul 2003"
 [8,] "Aug 1999" "Aug 2000" "Aug 2001" "Aug 2002" "Aug 2003"
 [9,] "Sep 1999" "Sep 2000" "Sep 2001" "Sep 2002" "Sep 2003"
[10,] "Oct 1999" "Oct 2000" "Oct 2001" "Oct 2002" "Oct 2003"
[11,] "Nov 1999" "Nov 2000" "Nov 2001" "Nov 2002" "Nov 2003"
[12,] "Dec 1999" "Dec 2000" "Dec 2001" "Dec 2002" "Dec 2003"
> ## 如果是矩阵则会转化成列向量进行计算
> matrix(1:8,nrow = 4,ncol = 2,byrow = T)
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
[4,]    7    8
> LETTERS
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R"
[19] "S" "T" "U" "V" "W" "X" "Y" "Z"
> outer(matrix(1:8,nrow = 4,ncol = 2,byrow = T),LETTERS[1:2],paste)
, , 1

     [,1]  [,2] 
[1,] "1 A" "2 A"
[2,] "3 A" "4 A"
[3,] "5 A" "6 A"
[4,] "7 A" "8 A"

, , 2

     [,1]  [,2] 
[1,] "1 B" "2 B"
[2,] "3 B" "4 B"
[3,] "5 B" "6 B"
[4,] "7 B" "8 B"

与此同时, outer(X, Y, FUN = “*”, …) 中的*可以是运算符号,例如"+“,”-"等等

> outer(1:2,2:4,"+")
     [,1] [,2] [,3]
[1,]    3    4    5
[2,]    4    5    6

因此按照这个逻辑来使用就很方便:

outer(X, Y, FUN = "*", ...)
X %o% Y

你可能感兴趣的:(r语言)