R

时间:2018-12-11 05:15:28

标签: r

嗨,我正在使用R,并且我有这样的数据:

1 2 3 4 5
1 2 1 2 2
3 4 1 2 3
1 2 3 4 5
3 4 1 2 3

对于上述示例,我想用相同的编号对相同的行进行编号

1 2 3 4 5 --> 1
1 2 1 2 2 --> 2
3 4 1 2 3 --> 3
1 2 3 4 5 --> 1
3 4 1 2 3 --> 3

有人知道如何在R中执行此操作(对于数字大小写和字符大小写)?

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

这是您的数据:

df <- data.frame(a=c(1,1,3,1,3), 
                 b=c(2,2,4,2,4), 
                 c=c(3,1,1,3,1), 
                 d=c(4,2,2,4,2), 
                 e=c(5,2,3,5,3))

方法1: 您需要使用data.table软件包才能执行以下方法:

library(data.table)
i <- interaction(data.table(df), drop=TRUE)
df.out <- cbind(df, id=factor(i,labels=length(unique(i)):1))

这将为您提供以下内容:

#  a b c d e  id
#1 1 2 3 4 5   1
#2 1 2 1 2 2   3
#3 3 4 1 2 3   2
#4 1 2 3 4 5   1
#5 3 4 1 2 3   2

方法2: 另一种方法是使用plyr程序包,如下所示:

library(plyr)
.id <- 0
df.out <- ddply(df, colnames(df), transform, id=(.id<<-.id+1))    

这将为您提供以下输出:

#  a b c d e  id
#1 1 2 1 2 2   1
#2 1 2 3 4 5   2
#3 1 2 3 4 5   2
#4 3 4 1 2 3   3
#5 3 4 1 2 3   3

希望有帮助。