Reputation: 899
I have many data frames similar to this:
count value
1 0 7
2 1 230
3 2 5
I want to add a column to assign colors according to the "value" column. The biggest one should be red, the second one should be blue, the smallest one should be green.
count value color
1 0 7 blue
2 1 230 red
3 2 5 green
Is there an easy way to do it in R? Thanks!
Upvotes: 1
Views: 2311
Reputation: 39154
We can use dplyr::case_when
.
dt <- data.frame(count = c(0, 1, 2), value = c(7, 230, 5))
library(dplyr)
dt2 <- dt %>%
mutate(color = case_when(
value == max(value) ~ "red",
value == min(value) ~ "green",
TRUE ~ "blue"
))
Or create the Rank
column first and then assign the values based on Rank
column.
dt2 <- dt %>%
mutate(Rank = dense_rank(value)) %>%
mutate(color = case_when(
Rank == 1 ~ "green",
Rank == 2 ~ "blue",
Rank == 3 ~ "Red"
)) %>%
select(-Rank)
Upvotes: 1
Reputation: 886938
We can use rank
from base R
to create the 'color'
df1$color <- c("green", "blue", "red")[rank(df1$value)]
Upvotes: 3
Reputation: 231
You can use dplyr
package
df <- data.frame(count = c(0,1,2), value = c(7,230,5))
df <- df %>%
mutate(color = ifelse(value == min(value), "green", ifelse(value == max(value), "red", "blue")))
Upvotes: 1