R使用unique时忽略NA

时间:2014-09-02 21:06:08

标签: r unique na

我试图根据列值的相似性来查找/丢弃行,并使用以下示例代码:

vec1 <- c("B","D","E","NA")    
vec2 <- c("B","D","E","NA")    
vec3 <- c("B","C","E","NA")    
vec4 <- c("B","D","E","NA")    
vec5 <- c("B","NA","E","E")    
vec6 <- c("B","NA","NA","NA")

mat1 <- cbind(vec1,vec2,vec3,vec4,vec5,vec6)
mat1
     vec1 vec2 vec3 vec4 vec5 vec6
[1,] "B"  "B"  "B"  "B"  "B"  "B" 
[2,] "D"  "D"  "C"  "D"  "NA" "NA"
[3,] "E"  "E"  "E"  "E"  "E"  "NA"
[4,] "NA" "NA" "NA" "NA" "E"  "NA"

rows = apply(mat1, 1, function(i) length(unique(i)) > 1 )
mat2 <- mat1[rows, ]
     vec1 vec2 vec3 vec4 vec5 vec6
[1,] "D"  "D"  "C"  "D"  "NA" "NA"
[2,] "E"  "E"  "E"  "E"  "E"  "NA
[3,] "NA" "NA" "NA" "NA" "E"  "NA"

如何更改上面的代码才能实现此目的?在unique的帮助文件中,它表明存在incomparables参数,是否已实现,是否可以使用?我不一定希望删除NA只是忽略它们。

2 个答案:

答案 0 :(得分:3)

来自上面的评论

rows = apply(mat1, 1, function(i) length(unique(i[!(i=="NA")]))>1)

答案 1 :(得分:1)

您需要为is.na正确输入它们才能正常工作。目前它们是字符串,NA已被归类为我们可以指定NA_character_是安全的。  另外,我建议summary以下是一些可以获取所需信息的表格。

length(unique(...))基本上是table

> mat1[is.na(mat1)]  
# character(0)  ## not good 
> mat1[mat1 == "NA"] <- NA_character_
> mat1[is.na(mat1)]  ## notice the difference...
# [1] NA NA NA NA NA NA NA NA

 > summary(mat1)
   vec1     vec2     vec3     vec4     vec5     vec6  
 B   :1   B   :1   B   :1   B   :1   B   :1   B   :1  
 D   :1   D   :1   C   :1   D   :1   E   :2   NA's:3  
 E   :1   E   :1   E   :1   E   :1   NA's:1           
 NA's:1   NA's:1   NA's:1   NA's:1       

> apply(mat1, 2, function(x) length(table(x)))
vec1 vec2 vec3 vec4 vec5 vec6 
   3    3    3    3    2    1 

> as.table(t(mat1))
     A B C D
vec1 B D E  
vec2 B D E  
vec3 B C E  
vec4 B D E  
vec5 B   E E
vec6 B