Search code examples
rpipemagrittr

How to turn many commands into one pipe command in r?


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")

Solution

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