Orhan Yazar
Orhan Yazar

Reputation: 909

Replace duplicate rows in data.table

I'm trying to replace values of duplicate rows in a data.table. Let's say u have

A <- c(1,2,3,4,4,6,4)
B <- c("a","b","c","d","e","f","g")
C <- c(10,11,23,8,8,1,3)
dt <- data.table(A,B,C)

I would like to do: dt[duplicated(dt,dt[,c(1,3)]),][,2] <- 0 to obtain

>dt
   A B  C
1: 1 a 10
2: 2 b 11
3: 3 c 23
4: 4 d  8
5: 4 0  8
6: 6 f  1
7: 4 g  3

Upvotes: 1

Views: 80

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70643

You could do

> A <- c(1,2,3,4,4,6,4)
> B <- c("a","b","c","d","e","f","g")
> dt <- data.table(A,B,C, stringsAsFactors = FALSE)
> C <- c(10,11,23,8,8,1,3)
> dt[dt[, j = duplicated(.SD), .SDcols = c("A", "C")], B := "0"]
> dt
   A B  C
1: 1 a 10
2: 2 b 11
3: 3 c 23
4: 4 d  8
5: 4 0  8
6: 6 f  1
7: 4 g  3

... but now seeing David's solution is way more concise...

Upvotes: 1

Related Questions