替换数值显然会随机替换

时间:2015-05-18 21:21:45

标签: r

我正在尝试用字符串替换数值,但是当我尝试下面的代码时,它会用不正确的字符串替换一些值。这是为什么?

library(igraph)
g<-graph.data.frame(df, directed=F)

V(g)$color<-as.numeric(df[,3]) #assign the "attrib_of_df" attribute as the vertex color
V(g)$color[V(g)$color<50]<-"yellow"
V(g)$color[V(g)$color>50 & V(g)$color<100]<-"orange"
V(g)$color[V(g)$color>100]<-"red"

初始V(g)$颜色:

> V(g)$color
  [1] "2"   "17"  "48"  "16"  "36"  "124" "7"   "41"  "58"  "19"  "84"  "133" "44"  "68"  "60"  "25"  "36"  "31"  "28"  "60"  "16"  "1"   "24"  "0"   "23"  "26"  "23"  "26"  "11" 
 [30] "35"  "5"   "24"  "6"   "64"  "73"  "31"  "26"  "122" "41"  "64"  "4"   "72"  "0"   "5"   "21"  "52"  "0"   "10"  "59"  "13"  "68"  "0"   "68"  "35"  "1"   "0"   "101" "23" 
 [59] "71"  "46"  "22"  "40"  "77"  "32"  "41"  "26"  "75"  "24"  "90"  "42"  "10"  "100" "24"  "0"   "33"  "26"  "49"  "0"   "7"   "43"  "34"  "26"  "17"  "50"  "24"  "9"   "20" 
 [88] "37"  "19"  "1"   "27"  "84"  "41"  "34"  "0"   "10"  "29"  "43"  "25"  "15"  "29"  "0"   "4"   "59"  "2"   "17"  "48"  "16"  "36"  "124" "7"   "41"  "58"  "19"  "84"  "133"
[117] "44"  "68" 

跑完第二行后(将&lt; 50转为黄色):

> V(g)$color
  [1] "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "7"      "yellow" "58"     "yellow" "84"     "yellow" "yellow" "68"     "60"     "yellow" "yellow" "yellow" "yellow"
 [20] "60"     "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "6"      "64"     "73"     "yellow" "yellow" "yellow"
 [39] "yellow" "64"     "yellow" "72"     "yellow" "yellow" "yellow" "52"     "yellow" "yellow" "59"     "yellow" "68"     "yellow" "68"     "yellow" "yellow" "yellow" "yellow"
 [58] "yellow" "71"     "yellow" "yellow" "yellow" "77"     "yellow" "yellow" "yellow" "75"     "yellow" "90"     "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow"
 [77] "yellow" "yellow" "7"      "yellow" "yellow" "yellow" "yellow" "50"     "yellow" "9"      "yellow" "yellow" "yellow" "yellow" "yellow" "84"     "yellow" "yellow" "yellow"
 [96] "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "59"     "yellow" "yellow" "yellow" "yellow" "yellow" "yellow" "7"      "yellow" "58"     "yellow"
[115] "84"     "yellow" "yellow" "68"  

我得到的值大于50变成黄色这个词,但其他值保持不变,为什么?

1 个答案:

答案 0 :(得分:2)

这是因为您的初始向量存储为字符串而不是数字,所以您要与字符串排序而不是数字排序进行比较:

x <- c("2", "7", "60")
x[x<50]<-"yellow"
x
# [1] "yellow" "7"      "60"  

可以使用as.numeric处理:

x <- c("2", "7", "60")
x[as.numeric(x)<50]<-"yellow"
x[as.numeric(x)>=50 & as.numeric(x) < 100] <- "orange"
x[as.numeric(x) >= 100] <- "red"
x
# [1] "yellow" "yellow" "orange"

这会产生一些警告,因为你在处理其他范围之前已经用颜色覆盖了部分字符串,所以实际上最好用一个嵌套的ifelse来一次处理:

x <- c("2", "7", "60")
x <- ifelse(as.numeric(x) < 50, "yellow", ifelse(as.numeric(x) >= 100, "red", "orange"))
x
# [1] "yellow" "yellow" "orange"