R中的ifelse陈述

时间:2014-01-11 04:20:12

标签: r if-statement

我在R中的用户生成函数内部,并希望某些代码行以参数为条件。例如,Position是函数的输入。如果此变量为2或4,我想显示或不显示轴。这是我所拥有的但它似乎不起作用。在R中这样的事情可能吗? (见代码第2行)

Themes <- theme(axis.title = element_text(size=fsizes),
                  if(Position == 2 | Position == 4, axis.text.x=element_blank() , axis.text.x = element_text(size=fsizes, color = "black")), 
                  axis.text.y = element_text(size=fsizes, color = "black"), 
                  title=element_text(size=fsizes), 
                  legend.text=element_text(size=fsizes-1.5),
                  legend.key.width = unit(.1, "cm"), legend.key.height = unit(.2, "cm"),
                  legend.position = "top",
                  legend.direction = "horizontal",
                  legend.margin = unit(0, 'cm'),
                  axis.ticks = element_line(size = .2),
                  panel.grid.major = element_line(size=.2),
                  panel.grid.minor = element_line(size=.1),
                  plot.margin = unit(c(.1,.1,.1,0), 'cm')
                  )

2 个答案:

答案 0 :(得分:2)

我相信`if`就是你在这里的目标。写?`if`寻求帮助,但想法是:

if(condition) expression

或在这种情况下:

if(condition) {
  expression 1
} else {
expression 2
}


ifelse(test, cond1, cond2) 

我认为用于测试函数中的简单条件并不常用。 当然,无论如何都要看看?ifelse

require(ggplot2)


theme_fun <- function(Position = NULL, fsizes = NULL){
  theme = theme(axis.title = element_text(size=fsizes), 
                 axis.text.y = element_text(size=fsizes, color = "black"), 
                 title=element_text(size=fsizes), 
                 legend.text=element_text(size=fsizes-1.5),
                 legend.key.width = unit(.1, "cm"), legend.key.height = unit(.2, "cm"),
                 legend.position = "top",
                 legend.direction = "horizontal",
                 legend.margin = unit(0, 'cm'),
                 axis.ticks = element_line(size = .2),
                 panel.grid.major = element_line(size=.2),
                 panel.grid.minor = element_line(size=.1),
                 plot.margin = unit(c(.1,.1,.1,0), 'cm')
  )

  if(Position == 2 | Position == 4){
    theme = theme + axis.text.x=element_blank()
  } else {
    theme = theme + axis.text.x = element_text(size=fsizes, color = "black")
  }
}

编辑澄清评论

x = "hello"

# This if else construct
if(x == "hello"){
  print("como va che?")
} else {
  "hello"
}

# Is equivalent to this
`if`(x == "hello", "como va che?", "hello")

评论的要点是澄清function是访问函数的另一种方式。 例如,如果您想阅读帮助。

?`if`

这是另一个例子:

`+`(1, 100)

答案 1 :(得分:1)

另一种方法是替换第二行代码:

if(Position == 2 | Position == 4, 
   axis.text.x=element_blank() , 
   axis.text.x = element_text(size=fsizes, color = "black")), 

用这个:

axis.text.x= ifelse(Position==2 | Position==4, 
                    element_blank(), 
                    element_text(size=fsizes, color = "black")),