Home > Back-end >  How to turn many commands into one pipe command in r?
How to turn many commands into one pipe command in r?

Time:11-16

I am very new to the pipe %>% operator. Can someone tell me if (and if yes, how) I can turn this into one or maybe two pipe commands?

b2m <- b$bdi.2m-b$bdi.pre
b2m %>%
  as.vector(mode = "any")
b2m <- b2m[!is.na(b2m)]
b2m <- b2m^2 
b2m <- sum(b2m)/length(b2m)
b2m

When I tried to resume the pipe after the 3rd line I always got errors with the indices.

Edit:

> dput(head(b))
structure(list(drug = structure(c(1L, 2L, 2L, 1L, 2L, 2L), .Label = c("No", 
"Yes"), class = "factor"), length = structure(c(2L, 2L, 1L, 2L, 
2L, 1L), .Label = c("<6m", ">6m"), class = "factor"), treatment = structure(c(1L, 
2L, 1L, 2L, 2L, 2L), .Label = c("TAU", "BtheB"), class = "factor"), 
    bdi.pre = c(29, 32, 25, 21, 26, 7), bdi.2m = c(2, 16, 20, 
    17, 23, 0), bdi.3m = c(2, 24, NA, 16, NA, 0), bdi.5m = c(NA, 
    17, NA, 10, NA, 0), bdi.8m = c(NA, 20, NA, 9, NA, 0)), row.names = c("1", 
"2", "3", "4", "5", "6"), class = "data.frame")

CodePudding user response:

b %>% summarise(b2m = sum((bdi.2m - bdi.pre)^2, na.rm = T)/length(bdi.2m))

CodePudding user response:

Here are a few approaches. The first uses magrittr %$%, the second uses %>%, the third uses |> from the base of R, the fourth does not use pipes and the fifth uses the bizarro pipe which is just a clever use of base syntax to simulate a pipe.

library(magrittr)

b %$% mean((bdi.2m - bdi.pre)^2, na.rm = TRUE)
## [1] 180.6666667

b %>% with(mean((bdi.2m - bdi.pre)^2, na.rm = TRUE))
## [1] 180.6666667

# remaining alternatives use only base R

b |> with(mean((bdi.2m - bdi.pre)^2, na.rm = TRUE))
## [1] 180.6666667

with(b, mean((bdi.2m - bdi.pre)^2, na.rm = TRUE))
## [1] 180.6666667

b ->.; with(., mean((bdi.2m - bdi.pre)^2, na.rm = TRUE))
## [1] 180.6666667

CodePudding user response:

You can do what you want with pipe. The problem you had come from the fact that the pipe give the result of the previous line as the first argument of the function, and because of that it will not work for something like b2m[!is.na(b2m)], because it is not a function (the function is inside the []). You need to tell R where to pass the result of the previous line and it can be done with a .

But it would not work for sum(b2m)/length(b2m), for a different reason: there is two functions so you need to transform it as one function (this can be done by putting this line between {}. Or you can separate the operations in two line.

A result of what you want can be:

b2m <- b$bdi.2m-b$bdi.pre
b2m %>%
  as.vector(mode = "any") %>%
  .[!is.na(.)] %>%
  .^2 %>%
  {sum(.)/length(.)}

This is a complement of what @Wilson Souza wrote, as it can be more readable, especially when you have to use lot of pipes with complicated functions.

  • Related