R语言 outer()函数
R编程语言中的outer()函数 ,用于对两个数组应用一个函数。
语法: outer(x, y, FUN=”*”, …)
参数
- x, y: 数组
- FUN: 在外层产品上使用的函数,默认值是multiply。
outer() 函数在R语言中的编程实例
例1:两个向量的外积
# R program to illustrate
# outer function
# Initializing two arrays of elements
x <- c(1, 2, 3, 4, 5)
y<- c(2, 4, 6)
# Multiplying array x elements with array y elements
# Here multiply (*) parameter is not used still this
# function take it as default
outer(x, y)
输出
[, 1] [, 2] [, 3]
[1, ] 2 4 6
[2, ] 4 8 12
[3, ] 6 12 18
[4, ] 8 16 24
[5, ] 10 20 30
例2:向量和单值的外层函数
# R program to illustrate
# outer function
# Initializing two arrays of elements
x <- 1:8
y<- 4
# Multiplying array x elements with array y elements
# Here multiply (*) parameter is not used still this
# function take it as default
outer(x, y, "+")
输出
[,1]
[1,] 5
[2,] 6
[3,] 7
[4,] 8
[5,] 9
[6,] 10
[7,] 11
[8,] 12