Home > Software engineering >  Create a matrix from a vector and flipping it using base pipe
Create a matrix from a vector and flipping it using base pipe

Time:08-31

I have the following vector:

v<-c(1,2,3,4,1,2,3,4,2) 

which I want to "transform" into a 3x3 matrix:

matrix <- matrix(data=v,ncol=3)

which I then want to "flip" over (not transpose)

flip_matrix<-matrix[,3:1,drop=FALSE]

It's very easy to use the tidyverse pipe to chain all this but to cut down dependencies I would like to sort this out using base R. I could do it creating several objects and forget about the pipe, but I need to know how this would be done with the base pipe. So far, I had no luck with:

v<-c(1,2,3,4,1,2,3,4,2)

final_matrix <- matrix(data=v,ncol=3) |> .[,3:1.drop=FALSE]()

Which tells me the object "." was not found. I've tried other iterations with no luck... Thanks for your help!

CodePudding user response:

Another way calling the function [.

v <- c(1,2,3,4,1,2,3,4,2)

matrix(data=v,ncol=3) |> `[`(x=_,,3:1, drop = FALSE)
#     [,1] [,2] [,3]
#[1,]    3    4    1
#[2,]    4    1    2
#[3,]    2    2    3

or without placeholder:

#Does not work as '[' is currently not supported in RHS call of a pipe
#matrix(data=v,ncol=3) |> `[`(,3:1, drop = FALSE)

#But the following will currently work
matrix(data=v,ncol=3) |> base::`[`(,3:1, drop = FALSE)
matrix(data=v,ncol=3) |> (`[`)(,3:1, drop = FALSE)

Or without pipe:

matrix(data=v,ncol=3)[, 3:1, drop = FALSE]
#matrix(v, ncol=3)[, 3:1] #Short alternative

CodePudding user response:

We could use a lambda function

matrix(data=v,ncol=3) |>
    {\(x) x[, 3:1, drop = FALSE]}()

-output

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

Or use Alias from magrittr

library(magrittr)
v |> 
  matrix(ncol = 3) |>
  extract(, 3:1)
      [,1] [,2] [,3]
[1,]    3    4    1
[2,]    4    1    2
[3,]    2    2    3
  •  Tags:  
  • r
  • Related