Pgibas Pgibas - 3 months ago 22
R Question

Optimize R chains (magrittr)

I would like to pipe (chain) magrittr object into loop. How can I do this?

I will use dummy operations/data as an example:

library(data.table)
library(magrittr)

# Dummy data modification
d <- mtcars %>%
setDT() %>%
.[, cylSQ := sqrt(cyl)] %>%
.[, carb3 := carb^3]
# Dummy loop
res <- list()
for(i in unique(d$gear)) {
res[[i]] <- d[gear == i] %>%
.[, lm(cylSQ ~ mpg + carb3 * wt)] %>%
.$fitted.values
}


Is it possible not to create object
d
and to pipe it directly to loop? For example:

for(i in unique(.$gear)) {
res[[i]] <- .[gear == i] %>%
...
}


Edit: I don't want to replace loop with
data.table
or
dplyr
, just curious about piping.

Answer

This is a bit of sketchy work around, but you can use the exposition operator in the magrittr package %$%.

I.e.:

mtcars %>% 
  filter(hp > 1) %$%
  for(i in 1:ncol(.)) {
    print(.[1,i])
  }

[1] 21
[1] 6
[1] 160
[1] 110
[1] 3.9
[1] 2.62
[1] 16.46
[1] 0
[1] 1
[1] 4
[1] 4