I've been experimenting with some new assignment functions for a few weeks and I like them more and more as their use becomes more natural to me.
`%like%` <- data.table::`%like%`
`%!like%` <- function(e1, e2){!e1 %like% e2}
`%!in%` <- function(x, table){!x %in% table}
`==<-` <- function(e1,e2,value) replace(e1, e1 == e2, value)
`!=<-` <- function(e1,e2,value) replace(e1, e1 != e2, value)
`<=<-` <- function(e1,e2,value) replace(e1, e1 <= e2, value)
`>=<-` <- function(e1,e2,value) replace(e1, e1 >= e2, value)
`><-` <- function(e1,e2,value) replace(e1, e1 > e2, value)
`<<-` <- function(e1,e2,value){
# this one needs extra care so standard base::`<<-` still works
if (missing(value))
eval.parent(substitute(.Primitive("<<-")(e1, e2)))
else
replace(e1, e1 < e2, value)
}
`%in%<-` <- function(e1,e2,value) replace(e1, e1 %in% e2, value)
`%!in%<-` <- function(e1,e2,value) replace(e1, !e1 %in% e2, value)
`%like%<-` <- function(e1,e2,value) replace(e1, e1 %like% e2, value)
`%!like%<-` <- function(e1,e2,value) replace(e1, !e1 %like% e2, value)
examples:
x <- 1:10
x > 5 <- 42
x
#> [1] 1 2 3 4 5 42 42 42 42 42
x <- c("ab","bc","cd")
x %!like% "b" <- "!!!"
x
#> [1] "ab" "bc" "!!!"
The last one I'm playing with is :
`~<-` <- function(e1,e2,value){ eval.parent(substitute(within(e1, {e2 <- value}))) }
iris2 <- head(iris)
iris2$Species <- as.character(iris2$Species)
iris2 ~ Species[Petal.Width > 0.3] <- "hello"
# equivalent to
# iris2$Species[iris2$Petal.Width > 0.3] <- "hello"