Magrittr%>% Operator for resizing matrix
I am doing my childish steps with an operator %>%
in R. This is extremely useful, but sometimes I get stuck on what should be simple.
Consider the following example:
mm<-matrix(nrow=4, ncol=5, seq(20))
dim(mm)<-NULL
which I am using for matrix smoothing. How can you smooth mm with %>%
?
One solution would be c()
:
mm %>% c
#[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
You can use the function:
set_dim_to_null <- function(mat) {
dim(mat) <- NULL
mat
}
mm %>%
set_dim_to_null()
Or use curly braces, which can act like an anonymous function:
mm %>% {
dim(.) <- NULL
.
}
mm %>% as.numeric
also gives the desired result.
Magrittr has several aliases for settings.
dim
not among them, but setters in R are really just functions with special names that end in <-
and return modified objects. So simply doing the following gives you a nicely named function that does what you want:
set_dim <- `dim<-`
You can use an alias like this or a simple mesh name in pipes:
mm %>% set_dim(NULL)
mm %>% `dim<-`(NULL)