【问题标题】:Error with the for loop code. The loop is not overwriting the values in the cloumn [duplicate]for 循环代码出错。循环没有覆盖 cloumn 中的值 [重复]
【发布时间】:2015-08-27 06:10:29
【问题描述】:

我想向我的数据框添加一个包含不同颜色的新列。这样我就可以在绘制该变量的点时使用 arg col 中的该列。

我想为同一范围内的值分配相同的颜色,为不同范围内的值分配不同的颜色。

例如,我有一个包含以下值的数据集:

> CN 

A    X
1    0.05
2    0.09
3    NA
4    0.12
5    0.35
6    0.21
7    NA
8    0.01
9    0.14
10   0.32
11   0.43
12   0.19

我想在我的数据框 CN 中添加一个单独的列 (Col)

> CN$Col <= "white" 

创建新栏目成功。我想为这些值中的每一个分配不同的颜色。并为NA 值分配white 或透明颜色。 即

<0.05      -- red
0.05 - 0.1 -- orange
0.1  - 0.2 -- yellow
0.2  - 0.3 -- green
0.3  - 0.4 -- darkviolet
0.4  - 0.5 -- blue

这是我写的代码

CN$Col <- "white"

for (i in 1:length(CN)) {
d <- is.na(CN$X[i])
 if (d == "FALSE") {
   if (CN$X[i] <= 0.05)
     CN$Col[i] <- "red"
   else if (CN$X[i] <= 0.1 && CN$X[i] > 0.05)
     CN$Col[i] <- "orange"
   else if (CN$X[i] <= 0.2 && CN$X[i] > 0.1)
     CN$Col[i] <- "yellow"
   else if (CN$X[i] <= 0.3 && CN$X[i] > 0.2)
     CN$Col[i] <- "green"
   else if (CN$X[i] <= 0.4 && CN$X[i] > 0.3)
     CN$Col[i] <- "darkviolet"
   else if (CN$X[i] <= 0.5 && CN$X[i] > 0.4)
     CN$Col[i] <- "blue"
 }
else
CN$Col[i] <- rgb(0, 0 , 0, alpha = 0) # rgb command can be replaced with color white
}

此代码不会覆盖我之前提供给该列的白色。

提前致谢。

【问题讨论】:

  • 或者你可以使用函数cut
  • 您可以简单地使用cut,其中一些(maube 需要如此调整)cut(CN$X, breaks = c(-Inf, 0.05, .1, .2, .3 , .4, .5), labels = c("red", "orange", "yellow", "green", "darkviolet", "blue"))
  • 这也是使用switch的好例子。
  • x &lt;- c("red", "orange", "yellow", "green", "darkviolet", "blue")[findInterval(CN$X, c(0.05, 0.1, 0.2, 0.3, 0.4))];replace(x, is.na(x), rgb(0, 0 , 0, alpha = 0))
  • 还有,for(i in 1:nrow(CN))

标签: r if-statement for-loop


【解决方案1】:

应该这样做!

for (i in 1:length(CN[,2])) {
  d <- is.na(CN$X[i])
  if (d == "FALSE") {
    if (CN$X[i] <= 0.05)
      CN$Col[i] = "red"
    else if (CN$X[i] <= 0.1 && CN$X[i] > 0.05)
      CN$Col[i] = "orange"
    else if (CN$X[i] <= 0.2 && CN$X[i] > 0.1)
      CN$Col[i] = "yellow"
    else if (CN$X[i] <= 0.3 && CN$X[i] > 0.2)
      CN$Col[i] = "green"
    else if (CN$X[i] <= 0.4 && CN$X[i] > 0.3)
      CN$Col[i] = "darkviolet"
    else if (CN$X[i] <= 0.5 && CN$X[i] > 0.4)
      CN$Col[i] = "blue"
  }
  else
    CN$Col[i] <- rgb(0, 0 , 0, alpha = 0) # rgb command can be replaced with color white
}

你定义的长度只有 3 而不是 12。

CN$Col[i] <= "orange"

这行也是一个错误。应该是:

CN$Col[i] = "orange"

希望这会有所帮助!

【讨论】:

  • 为什么不直接使用cut?更何况这是前阵子在cmets中提到的。
  • 我不知道cut 函数。我刚刚阅读了这个问题并给出了答案。就是这样……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
相关资源
最近更新 更多