【问题标题】:Mutate function only mutating first row, and then prints the same result for every subsequent row变异函数只变异第一行,然后为每个后续行打印相同的结果
【发布时间】:2017-08-24 15:20:22
【问题描述】:

我有一个数据框,其中包含一个具有十六进制颜色值的列。我想改变数据框,以便我可以在单独的列中拥有红色、蓝色和绿色值(rgb 格式),所以我使用来自 grDevices 包的 col2rgb 函数。这是我命名为 color_count 的数据框在变异之前的样子:

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

这是我改变数据框的代码:

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

这是输出:

      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

rgb 值仅对第一行正确,每隔一行仅显示完全相同的组合。

我尝试按照this other thread 的建议使用rowwise(),但没有成功。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:
    > 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 给你一个矩阵,所以你需要按 rows 而不是 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
    

    [] 中的索引后添加逗号意味着您正在按行和列而不是按元素进行索引。编号之前,是行索引,编号之后,是列索引。

    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
    

    【讨论】:

      【解决方案2】:

      这是一个避免在每一行中多次调用 col2rgb 的解决方案,而牺牲了使用一些更复杂的 tidyverse 操作

      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
      

      【讨论】:

        猜你喜欢
        • 2020-11-30
        • 2021-09-02
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多