How to extract unique levels from 2 columns in a data frame in r

I have data.frame

df<-data.frame("Site.1" = c("A", "B", "C"), "Site.2" = c("D", "B", "B"), "Tsim" = c(2, 4, 7), "Jaccard" = c(5, 7, 1)) # Site.1 Site.2 Tsim Jaccard # 1 AD 2 5 # 2 BB 4 7 # 3 CB 7 1 

I can get unique levels for each column using

 top.x<-unique(df[1:2,c("Site.1")]) top.x # [1] AB # Levels: ABC top.y<-unique(df[1:2,c("Site.2")]) top.y # [1] DB # Levels: BD 

How to get unique levels for both columns and turn them into ie vector:

 v <- c("A", "B", "D") v # [1] "A" "B" "D" 
+4
source share
3 answers
 top.xy <- unique(unlist(df[1:2,])) top.xy [1] ABD Levels: ABCD 
+2
source

Try union :

 union(top.x, top.y) # [1] "A" "B" "D" union(unique(df[1:2, c("Site.1")]), unique(df[1:2, c("Site.2")])) # [1] "A" "B" "D" 
+2
source

You can get unique levels for the first two columns:

 de<- apply(df[,1:2],2,unique) de # $Site.1 # [1] "A" "B" "C" # $Site.2 # [1] "D" "B" 

Then you can take the symmetric difference of the two sets:

 union(setdiff(de$Site.1,de$Site.2), setdiff(de$Site.2,de$Site.1)) # [1] "A" "C" "D" 

If you are only interested in the first two two lines (as in your example):

 de<- apply(df[1:2,1:2],2,unique) de # Site.1 Site.2 # [1,] "A" "D" # [2,] "B" "B" union(de[,1],de[,2]) # [1] "A" "B" "D" 
0
source

All Articles