Keep unique scores in each row of a data frame in R

Viewed 43

I have the following data frame in R, which have duplicated characters in each row.

i01 A   A   A   A   A   A
i02 B   C   D   B   C   D
i03 E   F   E   F   E   F
i04 G   G   G   G   G   G
i05 H   I   J   K   L   M
i06 N   O   P   N   O   P

I want to keep only the unique score in each row in the entire data frame, and replace the duplicate scores either by a blank or NA. Something like this:

i01 A   NA  NA  NA  NA  NA
i02 B   C   D   NA  NA  NA
i03 E   F   NA  NA  NA  NA
i04 G   NA  NA  NA  NA  NA
i05 H   I   J   K   L   M
i06 N   O   P   NA  NA  NA

I am trying by simply using unique function in the entire data frame but it doesn't work.

2 Answers

We can use duplicated to assign NA for those duplicates in a row

df1[-1] <- t(apply(df1[-1], 1, function(x) replace(x, duplicated(x), NA)))

data

df1 <- structure(list(id = c("i01", "i02", "i03", "i04", "i05", "i06"
), v1 = c("A", "B", "E", "G", "H", "N"), v2 = c("A", "C", "F", 
"G", "I", "O"), v3 = c("A", "D", "E", "G", "J", "P"), v4 = c("A", 
 "B", "F", "G", "K", "N"), v5 = c("A", "C", "E", "G", "L", "O"
 ), v6 = c("A", "D", "F", "G", "M", "P")), class = "data.frame", 
 row.names = c(NA, -6L))
as.data.frame(t(apply(df,1,function(x) ifelse(duplicated(x),NA,x))),stringsAsFactors=FALSE)

I see this is almost identical to @akrun's solution, only I used ifelse to his replace. same same...

Related