重命名 SAS 或 R 中的重复变量

Renaming duplicate variables in SAS or R

我正在尝试编写代码来创建一个新列,该列将用数字标记相应的化合物。我有在列表中重复的化合物,我需要用相同的数字标记这些化合物,但用字母分隔这些化合物。我不知道如何编码。谢谢,示例如下: 目前有:

Fructose 1
Maltose  2
Sucrose  3
Sucrose  4

想要什么:

    Fructose 1
    Maltose 2
    Sucrose 3
    Sucrose 3b

我无法手动标记每个化合物,因为我有这么大的数据集。

这是您问题的解决方案:

  1. 创建自定义格式 以映射 {1} -> {b}、{2} -> {c} 等
  2. 按碳水化合物列对您拥有的数据集进行排序
  3. 使用区间变量 First.Carbohydrate 如果这是碳水化合物的第一个实例,它将等于 1。
  4. 使用计数器跟踪重复值的数量。
  5. 现在使用自定义格式通过 put 函数将您的重复计数 转换为字母数字后缀:put(counter, customFormat.)

您可以阅读有关 by-group data step processing here 的内容来提高您的 SAS 技能。

下面是完整的工作示例:

    data have;
        length Carb ; 
        input Carb;
        datalines;
    Fructose
    Maltose 
    Sucrose 
    Sucrose 
    Sucrose 
    Pasta   
    Pasta   
    Rice   
    Rice 
    Rice
    Quinoa
    Bread
    ;

    proc format;
        value dupFormat
        1 = 'b'
        2 = 'c'
        3 = 'd'
        ;
    run;

    proc sort data=have;
        by Carb;
    run;

    data want(keep=Carb Number);
        length Carb ;
        length Number ;

        set have;
        by Carb;

        /* nCarbs is the number of distinct carbs written so far */
        if _n_=1 then nCarbs = 0;  

        if first.Carb then do;
            nCarbs+1;
            count_dup = 0; /* the number of duplicate records for the current cab */
            Number = left(put(nCarbs,3.)); 
        end;
        else do;
            count_dup+1;
            Number = cats(put(nCarbs,3.), put(count_dup, dupFormat.));
        end;
    run;

    proc print data=want;
    run;

以下是我将如何使用 R 和 data.table 包执行此操作。

首先,我们将按 compound 键控(和排序)数据。然后,我们将创建我们自己的索引并将字母添加到它的复制品中(尽管不确定您要如何处理大于 26 的组)

library(data.table)
setkey(setDT(df), compound)[, indx := as.character(.GRP), by = compound]
df[duplicated(df), indx := paste0(indx, letters[seq_len(.N)])]
df
#    compound number indx
# 1: Fructose      1    1
# 2:  Maltose      2    2
# 3:  Sucrose      3    3
# 4:  Sucrose      4   3a

使用@jaamor 的数据,您可以在 base r

中执行此操作
x <- c('Fructose','Maltose','Sucrose','Sucrose')
x <- c('Fructose','Maltose','Sucrose','Sucrose','Sucrose','Pasta',
       'Pasta','Rice','Rice','Rice','Quinoa','Bread')
y <- gsub('a', '', letters[ave(seq_along(x), x, FUN = seq_along)])

data.frame(x = x, y = paste0(cumsum(!duplicated(x)), y))

#           x  y
# 1  Fructose  1
# 2   Maltose  2
# 3   Sucrose  3
# 4   Sucrose 3b
# 5   Sucrose 3c
# 6     Pasta  4
# 7     Pasta 4b
# 8      Rice  5
# 9      Rice 5b
# 10     Rice 5c
# 11   Quinoa  6
# 12    Bread  7