I have two differents object
a list :
list_color <- c("#f87970", "#c59b04", "#5ab70b", "#04c195", "#06b7eb")
a dataframe :
head(data)
Cal Cre
1 ca h1
2 cb h2
3 ca h3
4 cd h4
5 ce h5
6 cb h2
7 ca h3
8 cd h4
I try to create a new column with a color corresponding to each value from "ca1" column
Cal Cre Color
1 ca h1 "#f87970"
2 cb h2 "#c59b04"
3 ca h3 "#f87970"
4 cd h4 "#5ab70b"
5 ce h5 "#04c195"
6 cb h2 "#c59b04"
7 ca h3 "#f87970"
8 cd h4 "#5ab70b"
I try to create a double loop, but it is not working. My code :
for(k in list_color){
for(i in data$Ca1){
data$Color <- ifelse(i , k, "None")
}
}
Try this approach without using loops with dataframes to identify unique values and then assign the color. The approach uses match()
. Here the code:
#Colors
list_color <- c("#f87970", "#c59b04", "#5ab70b", "#04c195", "#06b7eb")
dfcolors <- data.frame(id=1:length(list_color),list_color,stringsAsFactors = F)
#Unique values
uni <- unique(df$Ca1)
dfca1 <- data.frame(id=1:length(uni),uni,stringsAsFactors = F)
#Now match ca1 and colors
dfcolors$ca1 <- dfca1[match(dfcolors$id,dfca1$id),"uni"]
#Match with df
df$Color <- dfcolors[match(df$Ca1,dfcolors$ca1),"list_color"]
Output:
df
Ca1 Cre Color
1 ca h1 #f87970
2 cb h2 #c59b04
3 ca h3 #f87970
4 cd h4 #5ab70b
5 ce h5 #04c195
Some data used:
#Data
df <- structure(list(Ca1 = c("ca", "cb", "ca", "cd", "ce"), Cre = c("h1",
"h2", "h3", "h4", "h5")), row.names = c("1", "2", "3", "4", "5"
), class = "data.frame")
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments