【问题标题】:R - If else statement within for loopR - for 循环中的 If else 语句
【发布时间】:2014-07-20 15:23:16
【问题描述】:

我有一个包含 3 列数据的数据框,我想分别绘制 - 3 个图。数据中有 NA(在 3 列中的不同位置)。我基本上想插入缺失值并将线的那段(多个部分)绘制为红色,将线的其余部分绘制为黑色。

我已经设法使用“动物园”来创建插值数据,但不确定如何将这个数据点绘制成不同的颜色。我找到了以下Elegant way to select the color for a particular segment of a line plot? 但我想我可以使用带有 if else 语句的 for 循环来按照链接中的建议创建颜色列 - 我需要 3 个单独的颜色列,因为我有 3 个数据集。

感谢任何帮助 - 因为我不确定从哪里开始,所以无法提供真正的示例!谢谢

【问题讨论】:

  • 我建议你准备一个可重现的小例子。以下是有关如何进行的一些提示。 stackoverflow.com/questions/5963269/…
  • 从 SAS 或 SPSS 工作到 R 的人几乎总是这样,当他们应该首先查看 ?ifelse 时却不正确地找到 for( ){if ( ) {} else{} }
  • 感谢 BondedDust - 我同意它太复杂了。如果有人感兴趣,这是我用于此的代码 UN.GRACE$Col

标签: r if-statement for-loop plot


【解决方案1】:

这是我的解决方案。它假定NAs 仍然存在于原始数据中。这些将在第一个 plot() 命令中省略。然后该函数只循环 NAs。

如果您将plot() 命令从函数中取出,您可能会获得更好的控制。如所写,“...”被传递给 plot() 并且 type = "b" 图表被模仿 - 但将其更改为您想要的任何内容都很简单。

# Function to plot interpolated valules in specified colours.
PlotIntrps <- function(exxes, wyes, int_wyes, int_pt = "red", int_ln = "grey",
      goodcol = "darkgreen", ptch = 20, ...) {

  plot(exxes, wyes, type = "b", col = goodcol, pch = ptch, ...)

  nas <- which(is.na(wyes))
  enn <- length(wyes)

  for (idx in seq(nas)) {
    points(exxes[nas[idx]], int_wyes[idx], col = int_pt, pch = ptch)
    lines(
      x = c(exxes[max(nas[idx] - 1, 1)], exxes[nas[idx]],
        exxes[min(nas[idx] + 1, enn)]),
      y = c(wyes[max(nas[idx] - 1, 1)], int_wyes[idx],
        wyes[min(nas[idx] + 1, enn)]),
      col = int_ln, type = "c")

    # Only needed if you have 2 (or more) contiguous NAs (interpolations)
    wyes[nas[idx]] <- int_wyes[idx]
  }
}

# Dummy data (jitter() for some noise)
x_data <- 1:12
y_data <- jitter(c(12, 11, NA, 9:7, NA, NA, 4:1), factor = 3)
interpolations <- c(10, 6, 5)

PlotIntrps(exxes = x_data, wyes = y_data, int_wyes = interpolations, 
  main = "Interpolations in pretty colours!",
  ylab = "Didn't manage to get all of these")

干杯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多