clairsang
clairsang

Reputation: 125

Remove all columns that length(unique) ==1 in R

Could you help me, pls. I have a data.frame :

  tes1 test2 test3 test4 test5 test6 test7 test8 test9
1    1     0     1     1     1     0     0     1     0
2    0     0     0     0     0     0     0     1     0
3    0     0     1     0     1     0     0     0     0
4    0     0     1     0     0     0     1     1     0
5    0     1     1     1     1     0     0     1     0

I want to del test6 and test 9 ( length(unique) ==1) and keep all colnames remains.

Thanks.

Upvotes: 1

Views: 220

Answers (3)

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

# Select columns meeting the condition
colSel <- sapply( dat, function(x) length(unique(x))==1 )
# Use that logical vector to drop those columns
dat[ , !colSel ]

You can do it in one line by reversing the expression and using it in-line rather than saving it to a selector variable:

dat[ , sapply( dat, function(x) length(unique(x))>1 ) ]

sapply works here because data.frames are just lists, with each element being a column.

Upvotes: 6

djas
djas

Reputation: 1013

X = cbind( x=1, y=rnorm(10), w=rnorm(10), z =2)
keep = apply(X,2,function(x) length(unique(x))!=1)
Y = X[,keep]

Upvotes: 0

Matthew Lundberg
Matthew Lundberg

Reputation: 42649

Calling your data frame d, here is an expression which does this:

d[,apply(d, 2, FUN= function(x) length(unique(x))) != 1]
  tes1 test2 test3 test4 test5 test7 test8
1    1     0     1     1     1     0     1
2    0     0     0     0     0     0     1
3    0     0     1     0     1     0     0
4    0     0     1     0     0     1     1
5    0     1     1     1     1     0     1

Upvotes: 1

Related Questions