Execute several functions using pipeline

Viewed 36

I have a dataframe and in order to process it and create a new dataframe with the rows of interest I execute the next code, which works fine:

arrivals <- arrivals[, c(2, 40:64)]
arrivals <- arrivals[complete.cases(arrivals), ]
medias <- rowMeans(arrivals[3:26])

# We select rows that we are interested in
map <- arrivals[c(44,165,40,84,111,158,26), ]

I would like a way of doing this using pipelines.

Something like:

map <- arrivals[, c(2, 40:64)] %>%
       arrivals[complete.cases(arrivals), ] %>%
       arrivals[c(44,165,40,84,111,158,26), ]

However this doesn´t work.

2 Answers

We can use select/slice to subset the columns/rows respectively and filter out the NA elements in 'arrivals' with complete.cases

library(dplyr)
arrivals %>%
   select(2, 40:64) %>%
   filter(complete.cases(arrivals)) %>%
   mutate(medias = rowMeans(select(., 3:26), na.rm = TRUE)) %>%
   slice(44, 165, 40, 84, 111, 158, 26)

The logic is the same as of akrun. Here we use na.omit thus I think we don't need na.rm = TRUE to calculate the row means:

library(dplyr)
map <- arrivals %>% 
    select(2, 40:64) %>% 
    na.omit() %>% 
    mutate(medias = rowMeans(select(., 3:26))) %>% 
    slice(26, 40, 44, 84, 111, 158, 165)
Related