R:基于两个 Dataframe 之间的值的差异的颜色值

7cwmlq89  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(116)

我目前正在根据下面两列中的值的比较来为表中的值着色。但是,我不确定如何更改颜色,如果差异〉3(绿色),〈3(红色),差异+/- 3(蓝色)

mydata<-
School  col1    col2
A   2   10
A   10  7
A   12  31
B   0   3
B   5   2
B   5   1
B   7   7

期望输出

School  col1    col2    col1_color
A   2   10  red
A   10  7   blue
A   12  31  red
B   0   3   blue
B   5   2   green
B   5   1   green
B   7   7   blue

我的代码:

improvement_formatter <- formatter("span",
                                   style = x ~ style(color = ifelse(x > mydata$col1, "blue", ifelse(x < mydata$col2, "Red","green"))),
                                   x ~ icontext(ifelse(x<0, "arrow-up", "arrow-down"),x)
)
formattable(mydata, list(`mydata$col1` = improvement_formatter))
j2qf4p5b

j2qf4p5b1#

我通过ifelse()将两列的差值与所需的颜色值进行比较,得到了所需的输出。我将差值放在一列中,用于比较非蓝色输出。我创建了一个绝对值列,用于在进入ifelse嵌套时检查蓝色结果。

school <- c('A','A','A','B','B','B','B')
col1 <- c(2,10,12,0,5,5,7)
col2 <- c(10,7,31,3,2,1,7)
df111 <- data.frame(school=school,col1=col1,col2=col2)

df111$col1_color <- df111$col1 - df1$col2
df111$col2_color <- abs(df111$col1_color)

df111$col3_color <- ifelse(df111$col2_color == 3,'blue',
                         ifelse(df111$col1_color > 3,'green',
                                ifelse(df111$col1_color < 3,'red','')))

相关问题