ceth
ceth

Reputation: 45295

Create unique column in data frame

I have the data frame where the combination of three integer columns is unique.

Something like:

     p1_b p2_b p3_b b1 f1 b2 f2 b3  f3 
1       0    0    0  0 40  0 20  0 160 
2       0    0    1  0 40  0 20  4 152 

Combination of columns (p1_b + p2_b + p3_b) is unique. I need to create new integer unique column so it preserve the order of (p1_b + p2_b + p3_b) columns.

Something like:

> d <- transform(data, id = p1_b * 10000 + p2_b * 100 + p3_b)

but more R-specific.

Update:

To make my question more clear I give one example:

paste0( p1_b, p2_b, p3_b)

is not perfect solution as two rows with values (0 1 0) and (0 0 10) gives the same number 10.

Upvotes: 0

Views: 88

Answers (1)

user1317221_G
user1317221_G

Reputation: 15441

what about this..

transform(data, id = paste0( p1_b, p2_b, p3_b) )


#  p1_b p2_b p3_b b1 f1 b2 f2 b3  f3  id
#1    0    0    0  0 40  0 20  0 160 000
#2    0    0    1  0 40  0 20  4 152 001

EDIT


following your edit if you need an unique integer, then in 3 lines

data <- transform(data, ref = paste( p1_b, p2_b, p3_b, sep = ".") )
refDF <- data.frame(ref = unique(data$ref), id = 1:length(unique(data$ref)) )
merge(data, refDF, by = "ref" , all = TRUE)[-1]

#     p1_b p2_b p3_b b1 f1 b2 f2 b3  f3 id
#1    0    0    0  0 40  0 20  0 160  1
#2    0    0    1  0 40  0 20  4 152  2

# id is an integer running 1:n unique p1_b p2_b p3_b comninations

or in one line:

transform(data, id = as.integer(as.factor(paste( p1_b, p2_b, p3_b, sep = "."))))

Upvotes: 1

Related Questions