R: Using piping to pass a single argument to multiple locations in a function

蓝咒 提交于 2020-01-24 12:04:33

问题


I am attempting to exclusively use piping to rewrite the following code (using babynames data from babynames package:

library(babynames)
library(dplyr)

myDF <- babynames %>% 
group_by(year) %>% 
summarise(totalBirthsPerYear = sum(n))

slice(myDF, seq(1, nrow(myDF), by = 20))

The closest I have gotten is this code (not working):

myDF <- babyNames %>% 
group_by(year) %>% 
summarise(totalBirthsPerYear = sum(n)) %>% 
slice( XXX, seq(1, nrow(XXX), by = 20))

where XXX is meant to be passed via pipes to slice, but I'm stuck. Any help is appreciated.


回答1:


You can reference piped data in a different position in the function by using the . In your case:

myDF2 <- babynames %>%
    group_by(year) %>%
    summarize(totalBirthsPerYear = sum(n)) %>%
    slice(seq(1, nrow(.), by = 20))



回答2:


Not sure if this should be opened as a separate question & answer but in case anybody arrives here as I did looking for the answer to the MULTIPLE in the title: R: Using piping to pass a single argument to multiple locations in a function

Using the . from Andrew's answer in multiple places also achieves this.

[example] To get the last element of a vector vec <- c("first", "middle", "last") we could use this code.

vec[length(vec)]

Using piping, the following code achieves the same thing:

vec %>% .[length(.)] 

Hopefully this is helpful to others as it would have helped me (I knew about the . but couldn't get it working in multiple locations).



来源:https://stackoverflow.com/questions/43881601/r-using-piping-to-pass-a-single-argument-to-multiple-locations-in-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!