ks_18
ks_18

Reputation: 35

Mutate function only mutating first row, and then prints the same result for every subsequent row

I have a data frame that contains a column with hex color values. I want to mutate the data frame so that I can have the red, blue, and green values (rgb format) in separate columns, so I'm using the col2rgb function from grDevices package. This is what the data frame, which I named color_count, looks like before mutating:

      hex Count
    <chr> <int>
1 #00000B     3
2 #00000C    10
3 #00000D     1
4 #00000E    42
5 #00000F     4

Here's the code where I mutate the data frame:

color_rgb <- color_count %>%
  mutate(r = col2rgb(hex)[1], g = col2rgb(hex)[2], b = col2rgb(hex)[3])

This is the output:

      hex Count     r     g     b
    <chr> <int> <int> <int> <int>
1 #00000B     3     0     0    11
2 #00000C    10     0     0    11
3 #00000D     1     0     0    11
4 #00000E    42     0     0    11
5 #00000F     4     0     0    11

The rgb values are only correct for the first row, every other row just displays the exact same combination.

I tried using rowwise() as this other thread suggested, but it didn't work.

Upvotes: 1

Views: 1735

Answers (2)

owen88
owen88

Reputation: 474

Here's a solution which avoids multiple calls to col2rgb in each row with the sacrifice of using some more complex tidyverse manipulation

library(tidyverse)

color_rgb <- color_count %>%
  group_nest(hex, Count) %>%
  mutate(
    data = map(hex, ~col2rgb(.) %>% t %>% as_tibble)
  ) %>%
  unnest(data)

# A tibble: 5 x 5
#  hex     Count   red green  blue
#  <chr>   <dbl> <int> <int> <int>
# 1 #00000B     3    0     0    11
# 2 #00000C    10    0     0    12
# 3 #00000D     1    0     0    13
# 4 #00000E    42    0     0    14
# 5 #00000F     4    0     0    15

Upvotes: 0

acylam
acylam

Reputation: 18661

> col2rgb(color_count$hex)
      [,1] [,2] [,3] [,4] [,5]
red      0    0    0    0    0
green    0    0    0    0    0
blue    11   12   13   14   15

> class(col2rgb(color_count$hex))
[1] "matrix"

col2rgb gives you a matrix, so you need to index by rows instead of by elements:

> col2rgb(color_count$hex)[1,]
[1] 0 0 0 0 0
> col2rgb(color_count$hex)[2,]
[1] 0 0 0 0 0
> col2rgb(color_count$hex)[3,]
[1] 11 12 13 14 15

Adding a comma after your index in [] means that you are indexing by rows and columns instead of by element. Number before , is row index, while number after , is column index.

library(dplyr)

color_rgb <- color_count %>%
  mutate(r = col2rgb(hex)[1,], g = col2rgb(hex)[2,], b = col2rgb(hex)[3,])

#       hex Count r g  b
# 1 #00000B     3 0 0 11
# 2 #00000C    10 0 0 12
# 3 #00000D     1 0 0 13
# 4 #00000E    42 0 0 14
# 5 #00000F     4 0 0 15

Upvotes: 1

Related Questions