[R] Rows of a data frame to matrix

Gabor Grothendieck ggrothendieck at gmail.com
Mon Sep 25 21:54:22 CEST 2006


Using the builtin 11x8 anscombe data frame here are
some alternatives:

# 1
# list of 2x2 matrices
lapply(split(anscombe[1:4], 1:nrow(anscombe)), matrix, 2)

# 2
# 2x2x11 array
array(t(anscombe[1:4]), c(2, 2, nrow(anscombe)))

# 3
# to create matrix and perform calculations, e.g. det, all in one step
apply(anscombe[1:4], 1, function(x) det(matrix(x, 2)))



On 9/25/06, Damian Betebenner <damian.betebenner at bc.edu> wrote:
> useRs,
>
> I have a data frame where four of the columns of the data frame represent the values of a two-by-two
> matrix. I'd like to, row-by-row, go through the data frame and use the four columns, in matrix form, to
> perform calculations necessary to create new values for variables in the data frame. My first idea was to
> use apply:
>
> apply(as.array(data.frame[,1:4]), 1, matrix, nrow=2)
>
> Though intuitive, this doesn't work. I've stumbled in the dark with mApply and other functions but can't
> find anything in the help that works. This can't be that hard, but it has me stumped.
>
> Any help greatly appreciated,
>
> Damian
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list