0

I have a data frame (2 columns, some rows) and a function that takes a vector of 2 numbers and builds a matrix out of it. My goal is to apply that function on each row of the data frame such that in the end I have a list of matrices. I tried the following

df <- data.frame(c(1, 2, 3), c(4, 5, 6))
gen_mat <- function(x) matrix(c(x[1], x[1] + 1, x[2], x[2] +1), nrow = 2)
bad <- apply(df, 1, gen_mat)

Unfortunately, bad is not a list but a 4 by 3 matrix where each column contains the elements of one of the 3 generated matrices.

1 Answer 1

1

Is this it?

bad2 <- lapply(as.data.frame(t(df)), gen_mat)
bad2
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please elaborate on why your solution works and bad3 <- lapply(df, gen_mat) does not?
Because lapply is meant for objects of class list. Since a data.frameis a list where all elements, the columns, are of the same size, lapply will process one column at a time. Now, you need to process rows. So, transpose the df. But this makes of it a matrix. Then you have to coerce the matrix to data.frame.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.