简体   繁体   中英

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) 

Change your function to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM