我有两个不同的对象
列表:
list_color <- c("#f87970", "#c59b04", "#5ab70b", "#04c195", "#06b7eb")
一个数据框:
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
我尝试用颜色对应于“ ca1”列中每个值的颜色创建一个新列
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"
我尝试创建一个双循环,但它不起作用。 我的代码:
for(k in list_color){
for(i in data$Ca1){
data$Color <- ifelse(i , k, "None")
}
}
答案 0 :(得分:1)
尝试此方法时,不要在数据帧中使用循环来标识唯一值,然后分配颜色。该方法使用TestCompany
。这里的代码:
def loadfixtures(files):
def decorator(func):
def wrapped_func(*args, **kwargs):
for file in files:
df = pd.read_json(Path(datafolder).joinpath(file))
df.to_sql(file.split(".")[0], con=args[0].engine, index=False, if_exists='append')
return func(*args, **kwargs)
return wrapped_func
return decorator
输出:
match()
使用了一些数据:
#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"]
答案 1 :(得分:0)
我们可以在“ Ca1”的match
值上使用unique
df$Color <- list_color[match(df$Ca1, unique(df$Ca1))]
-输出
df
# Ca1 Cre Color
#1 ca h1 #f87970
#2 cb h2 #c59b04
#3 ca h3 #f87970
#4 cd h4 #5ab70b
#5 ce h5 #04c195
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")