4

我有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      A      D    2       5
#  2      B      B    4       7
#  3      C      B    7       1

我可以使用获得每列的唯一级别

top.x<-unique(df[1:2,c("Site.1")])
top.x

# [1] A B
# Levels: A B C

top.y<-unique(df[1:2,c("Site.2")])
top.y

# [1] D B
# Levels: B D

如何获得两列的唯一级别并将它们转换为向量,即:

v <- c("A", "B", "D")
v
# [1] "A" "B" "D"
4

3 回答 3

2

尝试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"
于 2012-07-22T14:39:00.200 回答
2
top.xy <- unique(unlist(df[1:2,]))
top.xy

[1] A B D
Levels: A B C D
于 2012-07-22T14:07:28.470 回答
0

您可以获得前两个列的唯一级别:

de<- apply(df[,1:2],2,unique)  
de

# $Site.1  
# [1] "A" "B" "C"  

# $Site.2  
# [1] "D" "B"  

然后你可以取两组的对称差:

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

如果您只对前两行感兴趣(如您的示例所示):

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"
于 2012-07-22T15:31:18.830 回答