带有两个if语句的循环不完整

时间:2017-11-21 10:43:45

标签: r for-loop if-statement

我现在在这个网站上搜索了很长时间,但一直无法找到我的问题的答案。

我正在研究一个小溪的几个属性之间的相关性,这些属性都是在一个数据框(PEQTfXS_GrooteMolenbeek)中收集的。目前我正专注于这条小溪的放电(PEQTfXS_GrooteMolenbeen $ Q)。我想要做的是在放电数据中运行for循环,如果当前值小于先前值,则指定颜色为红色。如果当前值大于先前值,则将分配蓝色。最后,如果可能的话,我想根据时间(PEQTfXS_GrooteMolenbeek $ date)创建红色和蓝色数据点的图。

我现在拥有的循环如下:

for (i in 1:length(PEQTfXS_GrooteMolenbeek$Q){
if PEQTfXS_GrooteMolenbeek$Q[i] < PEQTfXS_GrooteMolenbeek$Q[i-1] col = "red"
if PEQTfXS_GrooteMolenbeek$Q[i] > PEQTfXS_GrooteMolenbeek$Q[i-1] col = "blue"
}

这个循环似乎缺少一些东西,但我不知道是什么。除此之外,我想知道如何实现我的问题的绘图部分。

希望这个问题不是太愚蠢。我知道有比for循环更简单的方法,但我对那些不感兴趣;)

谢谢!

2 个答案:

答案 0 :(得分:2)

只需为您的条件创建一个因子变量编码,例如:

Peter

(在上面的代码中,对于值相等的情况没有规定。上面的代码会将这些情况放在第一组中)

然后,您可以使用例如 base PEQTfXS_GrooteMolenbeek$group <- NA PEQTfXS_GrooteMolenbeek$group[-1] <- PEQTfXS_GrooteMolenbeek$Q[-1] > PEQTfXS_GrooteMolenbeek$Q[-nrow(EQTfXS_GrooteMolenbeek)] PEQTfXS_GrooteMolenbeek$group <- as.factor(PEQTfXS_GrooteMolenbeek$group) plot()包创建绘图,并使用ggplot2变量来编码不同的颜色。类似的东西:

group

希望这有帮助。

答案 1 :(得分:2)

虽然我更喜欢Milan Valášek的解决方案,因为它更优雅的R风格,我想提供一个答案,其中涵盖了关于for循环和if语句的语法的部分问题。我使用了一些示例性数据,因为没有可重复的示例。我希望这在语法方面有所帮助。

#generate example data
#since your values are integers and your colour codes are characters
#you need separate columns to store them
#character vectors would not be allowed in an integer vector
#(of course you could turn the full vector to character,
#but this would be make the code unnecessarily complex)
values <- rep(c(1,2), 5)
value_color <- rep("", length(values))
df <- data.frame(values = values
                 , value_color = value_color
                 , stringsAsFactors = F)

#since you index i-1, the first entry needs to be decided manually
df[1, "value_color"] <- "red"

#first entry skipped due to manual assignment
#note the brackets around the definition of the loop indices
for (i in 2:length(values) ) {

  #note the brackets around the definition of the expression to
  #be checked via if
  #best practice is to use curly brackets and new line to open if statements
  #for better readability
  #the if statements checks the values in the numeric column called value...
  if (df[i, "values"] < df[i-1, "values"]) {

    #...and assigns the corresponding value in the character column
    df[i, "value_color"]  <- "red"

  } else if (df[i, "values"]  > df[i-1, "values"]) {

    df[i, "value_color"]  <- "blue"

  }
}

df

#      values value_color
# 1       1         red
# 2       2        blue
# 3       1         red
# 4       2        blue
# 5       1         red
# 6       2        blue
# 7       1         red
# 8       2        blue
# 9       1         red
# 10      2        blue
相关问题