【问题标题】:Label rows of unique combinations on two parameters in data.frame in R在R中data.frame中的两个参数上标记唯一组合的行
【发布时间】:2021-04-14 12:40:29
【问题描述】:

在包含两个参数(日期和电台)信息的 data.frame 中,我想标记 两者的每个独特组合都在一个新列中。

我有什么:

df
       date station  
1    april     GF3   
2 december     GF1    
3    april     GF2   
4    april     GF3     
5 december     GF1

我想要什么:

df2
       date station   Label
1    april     GF3      1
2 december     GF1      2 
3    april     GF2      3
4    april     GF3      1  
5 december     GF1      2 

谢谢!

【问题讨论】:

标签: r dataframe label unique multiple-columns


【解决方案1】:

将值粘贴在一起并使用match + unique 创建唯一的组号。

vals <- paste(df$date, df$station)
df$label <- match(vals, unique(vals))

#      date station label
#1    april     GF3     1
#2 december     GF1     2
#3    april     GF2     3
#4    april     GF3     1
#5 december     GF1     2

如果label 的编号不重要,您也可以在dplyr 中使用cur_group_id()

library(dplyr)
df %>% group_by(date, station) %>% mutate(label = cur_group_id()) %>% ungroup

【讨论】:

    【解决方案2】:

    dense_rank 也可以

    df %>% mutate(Label = dense_rank(paste(date, station)))
    
          date station Label
    1    april     GF3     2
    2 december     GF1     3
    3    april     GF2     1
    4    april     GF3     2
    5 december     GF1     3
    

    但是,它会优先按字母顺序排列数字

    【讨论】:

      【解决方案3】:

      dplyr 方法与left_join

      d <- tribble(~date, ~station,
                   "april","GF3",
                   "december","GF1",    
                   "april","GF2",   
                   "april","GF3", 
                   "december","GF1")
      
      d %>% left_join(
        d %>% distinct(date, station) %>% 
          rowid_to_column(),
        by = c("station", "date")
      )
      

      结果:

        date     station rowid
        <chr>    <chr>   <int>
      1 april    GF3         1
      2 december GF1         2
      3 april    GF2         3
      4 april    GF3         1
      5 december GF1         2
      

      【讨论】:

        猜你喜欢
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 2018-11-21
        • 1970-01-01
        • 2015-07-11
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        相关资源
        最近更新 更多