2014-12-04 59 views
1

我有一個R腳本,我正在將HTML顏色代碼應用於數據集中的特定羅馬數字值。我的代碼示例粘貼在下面。我在識別羅馬數字時遇到了問題。我還將包括我的數據樣本。我想用顏色代碼創建一個新列。使用羅馬數字html顏色名稱的R腳本

white = "#F0F8FF" 
aqua = "#00FFFF" 
black = "#000000" 
blue = "#0000FF" 
violet = "#8A2BE2" 
green = "#7FFF00" 
red = "#DC143C" 
dblue = "#191970" 
orange = "#FFA500" 
yellow = "#FFFF00" 
data <- read.csv("protiencs.csv") 
Data$Color <-{ 
for (i in data$MG){ 
    if (data$MG == II){ 
    data$Color <- white 
    } 
} 
} 

這裏是我的數據

  PI MG 
1 FC001547 II 
2 FC002108 III 
3 FC002109 III 
4 FC003548 IV 
5 FC003609 I 
6 FC003654-1 IV 

我所需的輸出是

PI MG Color 
FC001547 II #F0F8FF 
FC002108 III #00FFFF 

更正代碼

myDat <- read.csv("protiencs.csv", header = TRUE) 
myColors <- list(white = "#F0F8FF" 
       , aqua = "#00FFFF" 
       , black = "#000000" 
       , blue = "#0000FF" 
       , violet = "#8A2BE2" 
       , green = "#7FFF00" 
       , red = "#DC143C" 
       , dblue = "#191970" 
       , orange = "#FFA500" 
       , yellow = "#FFFF00") 
myDat$MG <- factor(myDat$MG, levels = c("II", "III", "IV", "I")) 
myDat$color <- myColors[myDat$MG] 
head(myDat) 

回答

0

您可以使用列表。 MG的內容是我假設的一個因素:

read.table(text = "PI MG 
1 FC001547 II 
2 FC002108 III 
3 FC002109 III 
4 FC003548 IV 
5 FC003609 I 
6 FC003654-1 IV", header = TRUE) -> myDat 

myColors <- list(white = "#F0F8FF" 
    , aqua = "#00FFFF" 
    , black = "#000000" 
    , blue = "#0000FF" 
    , violet = "#8A2BE2" 
    , green = "#7FFF00" 
    , red = "#DC143C" 
    , dblue = "#191970" 
    , orange = "#FFA500" 
    , yellow = "#FFFF00") 

myDat$MG <- factor(myDat$MG, levels = c("II", "III", "IV", "I")) 
myDat$color <- myColors[myDat$MG] 
> myDat 
      PI MG color 
1 FC001547 II #F0F8FF 
2 FC002108 III #00FFFF 
3 FC002109 III #00FFFF 
4 FC003548 IV #000000 
5 FC003609 I #0000FF 
6 FC003654-1 IV #000000 
+0

我似乎只獲得了顏色的NULL輸出。我已經用我試過的代碼更新了我的答案。請讓我知道,如果你有什麼錯誤的想法。 – user2524994 2014-12-04 16:01:22

+0

對不起,我錯過了你的代碼行。我糾正它,現在它的作品謝謝你! – user2524994 2014-12-04 16:04:17