在 dplyr 中使用过滤器以 R 中的 if 语句为条件 [英] Use filter in dplyr conditional on an if statement in R

查看:19
本文介绍了在 dplyr 中使用过滤器以 R 中的 if 语句为条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我分享一个我正在尝试做的示例,因为标题可能不像我希望的那样清晰.这没有可重现的代码,但如果有帮助,我可以添加一个可重现的示例:

Let me share an example of what I'm trying to do, since the title may not be as clear as I'd like it to be. This doesn't have reproducible code, but i can add a reproducible example if that will help:

library(dplyr)
if(this_team != "") {
  newdf <- mydf %>%    
      filter(team == this_team) %>%
      mutate(totalrows = nrow(.)) %>%
      group_by(x1, y1) %>%
      summarize(dosomestuff)
} else {
  newdf <- mydf %>%    
      filter(firstname == this_name & lastname == that_name) %>%
      mutate(totalrows = nrow(.)) %>%
      group_by(x1, y1) %>%
      summarize(dosomestuff)
}

我正在 R 中创建一个函数,该函数对 mydf 数据帧执行一些数据操作.如果我将一个值传递给函数的 team_name 参数,那么我想使用团队"列过滤数据框.如果我不传递一个值team_name 参数,然后它默认为 "",我改为传递 this_name 和 that_name 的值,它们对应于 mydf 中的列 'firstname' 和 'lastname'.

I am creating a function in R that does some data manipulations on the mydf dataframe. If I pass a value to the function's team_name parameter, then I would like to filter the dataframe using the 'team' column. If I don't pass a value to the team_name parameter, then it defaults to "", and I instead pass values for this_name and that_name, which correspond to the columns 'firstname' and 'lastname' in mydf.

有没有更好的方法来做到这一点,而不必在两个单独的 if else 语句中再次创建整个 dplyr 管道?我的实际代码管道每条都比 4 行长得多,因此不得不像这样重现代码非常令人沮丧.

Is there a better way to do this, rather than having to create the entire dplyr pipeline again in two separate if else statements? My actual pipeline of code is much longer than 4 lines each, so having to reproduce code like this is quite frustrating.

推荐答案

You can do

library(dplyr)
y <- ""
data.frame(x = 1:5) %>% 
  {if (y=="") filter(., x>3) else filter(., x<3)} %>% 
  tail(1)

data.frame(x = 1:5) %>% 
 filter(if (y=="") x>3 else x<3) %>%  
  tail(1)

甚至将您的管道存放在

mypipe <- . %>% tail(1) %>% print
data.frame(x = 1:5) %>% mypipe

这篇关于在 dplyr 中使用过滤器以 R 中的 if 语句为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆