Make all items unique in the data area

Assuming I have data as shown below.

On all these data in general, I have 3 * A, 2 * B, 2 * C and only 1 D, E and F.

data <- read.table(textConnection("
col1 col2 
A B
A C
B A
C D
E F
"), header = TRUE)

What I want to do is keep order and content, but make them unique. For example, A becomes A.1, A.2, and A.3.

col1 col2 
A.1 B.2
A.2 C.2
B.1 A.3
C.1 D
E F

Is there any smart way to do this?

I know that I can use make.uniqueor make.names, but it seems that it can work for only one column, and not for the entire data set.

+5
source share
3 answers

unlist , ave, , paste

v1 <- as.character(unlist(data))
data[] <- sub("\\.$", "", paste(v1, ave(v1, v1,
         FUN = function(x) if(length(x)>1) seq_along(x) else ""), sep="."))
data
#  col1 col2
#1  A.1  B.2
#2  A.2  C.2
#3  B.1  A.3
#4  C.1    D
#5    E    F
+2

:

dat[] <- make.unique(as.character(unlist(dat)))

:

> dat
  col1 col2
1    A  B.1
2  A.1  C.1
3    B  A.2
4    C    D
5    E    F
+5

OP , data.frame . , , , .

library(data.table)
DT <- data.table(data)
molten <- melt(DT, measure.vars = names(DT))[
  , value := paste(value, rowid(value), sep = ".")]
molten
    variable value
 1:     col1   A.1
 2:     col1   A.2
 3:     col1   B.1
 4:     col1   C.1
 5:     col1   E.1
 6:     col2   B.2
 7:     col2   C.2
 8:     col2   A.3
 9:     col2   D.1
10:     col2   F.1

rowid() .

. , :

molten[, rn := rowid(variable)][, dcast(.SD, rn ~ variable)][, rn := NULL][]
   col1 col2
1:  A.1  B.2
2:  A.2  C.2
3:  B.1  A.3
4:  C.1  D.1
5:  E.1  F.1

Jaap make.unique():

melt(DT, measure.vars = names(DT))[, value := make.unique(value)][]
    variable value
 1:     col1     A
 2:     col1   A.1
 3:     col1     B
 4:     col1     C
 5:     col1     E
 6:     col2   B.1
 7:     col2   C.1
 8:     col2   A.2
 9:     col2     D
10:     col2     F
+4

All Articles