elliot
elliot

Reputation: 1944

Margrittr pipe with matrix operations in R

I'm working on some functions that take a matrix as input and provide a matrix as output. Is it possible to use the magrittr pipe with matrices without using the . placeholder? Ideally, I'd like these functions to be piped into each other like a dplyr chain. The issue is that I'm constantly forgetting to specify the . placeholder and getting errors.

library(magrittr)
set.seed(123)
m <- matrix(rnorm(10), ncol = 2)  

# This works perfectly:
layout_align_x <- function(n = nodes, anchor, m = matrix){
  m[n, 1] <- m[anchor, 1]
  return(m)}

# This also works perfectly:
layout_align_x(c(1,2), 3, m)

# And this also: 
m %>% layout_align_x(c(1,2), 3, .)

# This returns error: 
m %>% layout_align_x(c(1,2), 3)
#Error in m[anchor, 1] : incorrect number of dimensions

# The goal is:
m %>% 
  layout_align_x(c(1,2), 3) %>% 
  layout_align_x(c(3,4), 5) 

Upvotes: 2

Views: 654

Answers (1)

Hector Haffenden
Hector Haffenden

Reputation: 1369

Change your function to

layout_align_x <- function(m = matrix, n = nodes, anchor){
  m[n, 1] <- m[anchor, 1]
  return(m)
}

Upvotes: 4

Related Questions