简体   繁体   English

R中具有矩阵运算的Margrittr管

[英]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 . 是否可以在不使用的情况下将magrittr管与矩阵一起使用. placeholder? 占位符? Ideally, I'd like these functions to be piped into each other like a dplyr chain. 理想情况下,我希望这些函数像dplyr链一样通过管道相互dplyr 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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