简体   繁体   English

在 r 中应用函数(带有矩阵和函数)

[英]apply function in r (with matrix and function)

I am trying to make 3 rows and 8 columns matrix with apply function to simplify the code, but I have problem... I have to make matrix like this :我正在尝试使用 apply 函数制作 3 行 8 列矩阵以简化代码,但我有问题......我必须制作这样的矩阵:

    [,1] [,2] [,3]

[1,]    1    1    1

[2,]    2    4    3

[3,]    3    9    6

[4,]    4   16   10

[5,]    5   25   15

[6,]    6   36   21

[7,]    7   49   28

[8,]    8   64   36
x <- matrix(1:8,8,3)
x
m <- apply(x,2,function(z) return(c(z,z^2,(z^2+z)%/%2)))
m

We create a list of functions and loop through the columns with for loop, apply the corresponding functions我们创建一个函数list并使用for循环遍历列,应用相应的函数

f1 <- list(function(x) x, function(x) x^2, function(x) (x^2 + x)%/%2)
for(i in seq_len(ncol(x))) x[,i] <- f1[[i]](x[,i])
x
#      [,1] [,2] [,3]
#[1,]    1    1    1
#[2,]    2    4    3
#[3,]    3    9    6
#[4,]    4   16   10
#[5,]    5   25   15
#[6,]    6   36   21
#[7,]    7   49   28
#[8,]    8   64   36

In the OP's solution, the apply is looping through each column, but each of the functions is applied to all the columns and the results are concatenated.在 OP 的解决方案中, apply循环遍历每一列,但每个函数都应用于所有列,并且结果被连接起来。

The apply function applies a function to the margins of an array or matrix. apply函数apply函数应用于数组或矩阵的边距。 You are using the apply function in a correct way, so the anonymous function is being applied to each column of the input matrix and returning a matrix.您正在以正确的方式使用apply函数,因此匿名函数被应用于输入矩阵的每一列并返回一个矩阵。 The only thing is that the columns of your input matrix are similar so all columns in the output matrix will be similar too.唯一的问题是输入矩阵的列相似,因此输出矩阵中的所有列也相似。

There is a simpler solution to obtain your output matrix:有一个更简单的解决方案来获得您的输出矩阵:

x <- 1:8
f <- function(z) c(z,z^2,(z^2+z)%/%2)
m <- matrix(f(x), nrow = nrow(x), ncol = 3)

Although it doesn't use apply , I hope it helps.虽然它不使用apply ,但我希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM