Hi all,

There are matrices with same column names but arranged in different orders
and I desire columns of these matrices to have same order.

For example, below are 2 arbitrary data sets with columns arranged in
different order. I require columns of these to have same order as specified
in "columns" object and the results stored in the original object names.
I know this can be done simply by:
D1 <- D1[, columns]

But if there are hundreds of matrices, then more efficient method is
required.

columns <- c("A", "B", "C")
D1 <- matrix(rnorm(6), nrow = 2, dimnames = list(c("R1", "R2"), c("C", "A",
"B")))
D2 <- matrix(rnorm(6), nrow = 2, dimnames = list(c("R1", "R2"), c("C", "B",
"A")))

> D1
                    C                            A                        B
R1 -0.653978178594122 -0.15910510749630 0.90507729153852
R2  0.015557641181675 -0.73944224596032 0.23484927168787
> D2
                  C                           B                            A
R1 0.18843559757623 0.207589297797905 -0.018884844424975
R2 1.87387725184456 0.050349118287824 -1.796404635019739

Dlist <- list(D1, D2)
lapply(Dlist, function(x) x[, columns])

[[1]]
                   A                           B                          C
R1 -0.15910510749630 0.90507729153852 -0.653978178594122
R2 -0.73944224596032 0.23484927168787  0.015557641181675
[[2]]
                    A                          B                          C
R1 -0.018884844424975 0.207589297797905 0.18843559757623
R2 -1.796404635019739 0.050349118287824 1.87387725184456
How can the results from the lapply function be stored back into the
original object names?

Many thanks.



-- 
Steven

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org 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.

Reply via email to