📜  在 R 编程中对元素列表应用函数– lapply()函数

📅  最后修改于: 2022-05-13 01:54:27.028000             🧑  作者: Mango

在 R 编程中对元素列表应用函数– lapply()函数

R 编程语言中的lapply()函数用于将函数应用于元素列表。

R – 在元素列表上应用函数

示例 1:R 编程中 lapply()函数的基本示例

R
# R program to illustrate
# lapply() function
   
# Creating a matrix
A = matrix(1:9, 3, 3)
   
# Creating another matrix
B = matrix(10:18, 3, 3) 
   
# Creating a list
myList = list(A, B)
   
# applying lapply()
determinant = lapply(myList, det)
print(determinant)


R
# R program to illustrate
# lapply() function
   
# Creating a matrix
A = matrix(1:9, 3, 3)
   
# Creating another matrix
B = matrix(10:18, 3, 3) 
   
# Creating a list
myList = list(A, B)
   
# applying lapply()
sum = lapply(myList, sum)
print(sum)


输出:

[[1]]
[1] 0

[[2]]
[1] 5.329071e-15

示例 2:对 R 中的元素列表应用函数

R

# R program to illustrate
# lapply() function
   
# Creating a matrix
A = matrix(1:9, 3, 3)
   
# Creating another matrix
B = matrix(10:18, 3, 3) 
   
# Creating a list
myList = list(A, B)
   
# applying lapply()
sum = lapply(myList, sum)
print(sum)

输出:

[, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1]  28  80 162
[1]   6 120 504