Reputation: 1378
I am attempting to find/discard rows based on their similarity in column values and have the following example code:
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"
How may I change the code above to achieve this? In the help file for unique
it suggests there is an incomparables
argument, is this implemented and can it be used? I don't necessarily wish to remove the NA
's just ignore them.
Upvotes: 1
Views: 5140
Reputation: 99331
You'll need them to be properly entered for is.na
to work as it should. Currently they are character strings, and NA
has is classed to we can assign NA_character_
to be safe.
Also, I would recommend a summary
Here are a few table that get the information you need.
length(unique(...))
is essentially a 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
Upvotes: 1
Reputation: 3188
From comment above
rows = apply(mat1, 1, function(i) length(unique(i[!(i=="NA")]))>1)
Upvotes: 3