【问题标题】:R Program: Have dataframe with non-unique IDs. Need to create column with unique IDsR 程序:具有具有非唯一 ID 的数据框。需要创建具有唯一 ID 的列
【发布时间】:2021-01-11 20:12:08
【问题描述】:

我有一个具有唯一值的重复 ID 的数据框。我需要使 ID 唯一。

df <- read.csv("test.csv")

ID: A1, A1, A2, A2, A3, A3, A4, A4  
Value: 0.5, 0.9, 1.5, 0.8, 2.2, 2.4, 3.1, 0.5

我需要得到这个数据框:

ID: A1_1, A1_2, A2_1, A2_2, A3_1, A3_2, A4_1, A4_2  
Value: 0.5, 0.9, 1.5, 0.8, 2.2, 2.4, 3.1, 0.5

我尝试了以下代码,它添加了一个重复交替 _1 和 _2 的列并连接到 ID:

unique <- c("_1", "_2")  
Unique.col <- matrix(rep(unique, ))  
unique_ID <- cbind(df, Unique.col)  
unique_ID$ID <- paste(unique_ID$ID, unique_ID$Unique.col)  
unique_ID

我得到以下数据框,其中 A1 和 _1 之间有一个空格:

ID: A1 _1, A1 _2, A2 _1, A2 _2, A3 _1, A3 _2, A4 _1, A4 _2  
Value: 0.5, 0.9, 1.5, 0.8, 2.2, 2.4, 3.1, 0.5

有没有更好的方法或摆脱空间的方法?

【问题讨论】:

  • 在您的方法中使用paste0 而不是paste
  • 感谢 markus 和大家的快速回复。我使用了 paste0 并且成功了。

标签: r dataframe unique


【解决方案1】:

解决此问题的一般dplyr/tidyr 方法是将pivot_longerpivot_wider 一起使用:加长,然后按原始列名分组并创建唯一的组内ID,然后放宽。这似乎有点偏离了通常的旋转精神,但它完成了工作!

样本数据:

df <- tribble(
    ~"A1", ~"A1", ~"A2", ~"A2", ~"A3", ~"A3", ~"A4", ~"A4",
    1, 2, 3, 4, 5, 6, 7, 8
)

要创建唯一的组内 ID,请参阅 this answer。为了将这些 ID 与原始列名结合起来,tidyr 旋转小插图有一些很好的例子(例如here)。关键是使用names_from 参数将原始列名与新ID 结合起来。这让我们:

df %>%
    # Pivot original column names to "name" column and original values to "value" column
    pivot_longer(cols=everything()) %>%
    # Create unique IDs within each original column
    group_by(name) %>%
    mutate(row_id=row_number()) %>%
    # Pivot back to the desired wider format
    pivot_wider(names_from=c(name, row_id))

输出:

# A tibble: 1 x 8
   A1_1  A1_2  A2_1  A2_2  A3_1  A3_2  A4_1  A4_2
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     2     3     4     5     6     7     8

我们还可以将调用中的新列名的格式更改为pivot_wider,使用names_sep(默认为_)或names_pattern(采用正则表达式)。

【讨论】:

    【解决方案2】:

    您可以使用gsub(" ","",unique_ID) 删除空格

    例子:

    unique_ID <- c("A1 _1", "A1 _2", "A2 _1", "A2 _2", "A3 _1", "A3 _2", "A4 _1", 
    "A4 _2")
    test <- gsub(" ","",unique_ID)
    
    > test
    [1] "A1_1" "A1_2" "A2_1" "A2_2" "A3_1" "A3_2" "A4_1"
    [8] "A4_2"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      相关资源
      最近更新 更多