简体   繁体   中英

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.

Don't you mind using dplyr instead of data.table here? If not, try this:

library(dplyr)
d <- mtcars %>% 
    mutate(cylSQ = sqrt(cyl), carb3 = carb^3) %>% 
    group_by(gear) %>% 
    do(fitted.values = lm(cylSQ ~ mpg + carb3 * wt, data = .)[["fitted.values"]])

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

Ie:

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

I'm not magrittr practitioner so it could probably be improved, but at least works, and should be efficient.

as.data.table(mtcars
              )[, cylSQ := sqrt(cyl)
                ][, carb3 := carb^3
                  ][, lm(cylSQ ~ mpg + carb3 * wt)$fitted.values, by=gear
                    ] %>% 
    split(by = "gear", keep.by = FALSE) %>% 
    lapply(unlist) %>% 
    lapply(unname) -> res

Due to new split.data.table it requires data.table in 1.9.7, see installation wiki for details how to install on various platforms.

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