l0110
l0110

Reputation: 899

r assign characters to a column according to values

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

Answers (3)

www
www

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

akrun
akrun

Reputation: 886938

We can use rank from base R to create the 'color'

df1$color <- c("green", "blue", "red")[rank(df1$value)]

Upvotes: 3

Rafael Cunha
Rafael Cunha

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

Related Questions