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 :
[,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
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.
The apply
function applies a function to the margins of an array or matrix. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.