Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

r - How to define a function in dplyr?

I created a simple pivot table in the dplyr package in R. Here is my working example:

library(dplyr)
mean_mpg <- mean(mtcars$mpg)

# creating a new variable that shows that Miles/(US) gallon is greater than the mean or not

mtcars <-
mtcars %>%
  mutate(mpg_cat = ifelse(mpg > mean_mpg, 1,0))

mtcars %>%
  group_by(as.factor(cyl)) %>%
  summarise(sum=sum(mpg_cat),total=n()) %>%
  mutate(percentage=sum*100/total)

Now, I want to write a function to reuse this code:

get_pivot <- function(data, predictor,target) {
  result <-
    data %>%
    group_by(as.factor(predictor)) %>%
    summarise(sum=sum(target),total=n()) %>%
    mutate(percentage=sum*100/total);

  print(result)
}

but I receive the following error:

Error in is.factor(x) : object 'cyl' not found

I also tried

get_pivot(mtcars, "cyl", "mpg_cat" )

but it did not work.

What should I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have the most recent rlang library update v0.4.0 (June 2019), you can use double curly brackets {{ }} (aka "curly curly") to make programming with dplyr easier.

# Note: needs installation of rlang 0.4.0 or later
get_pivot <- function(data, predictor,target) {
  result <-
    data %>%
    group_by(as.factor( {{ predictor }} )) %>%
    summarise(sum=sum( {{ target }} ),total=n()) %>%
    mutate(percentage=sum*100/total);

  print(result)
}

# Edit -- thank you Rui Barradas
> get_pivot(mtcars, cyl, mpg_cat)
# A tibble: 3 x 4
  `as.factor(cyl)`   sum total percentage
  <fct>            <dbl> <int>      <dbl>
1 4                   11    11      100  
2 6                    3     7       42.9
3 8                    0    14        0  

The reason this is required is that dplyr and other tidyverse packages use "non-standard evaluation" like you encounter with some base R functions, like lm(mpg~factor(am),data=mtcars). This practice often makes "interactive" code shorter, simpler, and easier to read, but at the cost of making programming more complicated. In this case, the {{ }} operator serves to transport the column you specify into the context of the function.

https://www.tidyverse.org/articles/2019/06/rlang-0-4-0/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...