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

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

问题描述

让我分享一个我想做的事的例子,因为标题可能不尽如人意。这没有可复制的代码,但是如果有帮助,我可以添加一个可复制的示例:

  library(dplyr)
if(this_team!=){
newdf<-mydf%>%
filter(team == this_team)%&%;%
mutate(totalrows = nrow(。 ))%>%
group_by(x1,y1)%&%;%
summary(dosomestuff)
}否则{
newdf<-mydf%&%;%
filter(firstname == this_name& lastname == that_name)%>%
mutate(总数= nrow(。))%>%
group_by(x1,y1)%>%
summary(dosomestuff)
}

我正在R中创建一个函数在mydf数据帧上进行一些数据操作。如果我将一个值传递给函数的team_name参数,那么我想使用团队列过滤数据框。如果我没有将team_name参数的值传递给
,则它默认为,而是传递this_name和that_name的值,它们对应于mydf中的 firstname和 lastname列。 / p>

是否有更好的方法来执行此操作,而不是必须在两个单独的if语句中再次创建整个dplyr管道?我实际的代码流水线每个都比4行长得多,因此不得不重现这样的代码非常令人沮丧。

解决方案

您可以做到

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

  data.frame(x = 1:5)%>%
过滤器(如果(y ==)x> 3 else x< 3)%&%;
tail( 1)

甚至将管道存储在


$ b的静脉中$ b

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


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

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.

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 could do

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

or

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

or even store your pipe in the veins of

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

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

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