Barnaby
Barnaby

Reputation: 1480

extract column names from a data frame which includes other than zero

1I have a vector of objects each one corresponding to a columns of numbers and would like to produce a vector of names with only the names in the vector for which their columns are not only zeros.

a<-c(0,0,0,0,0,0,0,0,0,0,0,0)
b<-c(1,3,2,5,4,2,1,5,6,7,3,2)
c<-c(0,0,0,0,0,0,0,0,0,0,0,0)
d<-c(1,1,4,5,2,2,1,1,6,2,3,3)
e<-c(0,0,0,0,0,0,0,0,0,0,0,0)
f<-c(1,3,2,5,4,2,1,5,6,7,3,2)
g<-c(0,0,0,0,0,0,0,0,0,0,0,0)
h<-c(1,1,4,5,2,2,1,1,6,2,3,3)

x<-data.frame(a,b,c,d,e,f,g,h)

x<- x[x != "0"]

Extracts a vector of all the elements that are non zero undiferenced by column, however I like to extract all column names that do not have only zero rows.

Thank you

Upvotes: 0

Views: 708

Answers (3)

jlhoward
jlhoward

Reputation: 59385

Similar to the others.

names(x)[colSums(x)>0]
# [1] "b" "d" "f" "h"

Upvotes: 1

Sven Hohenstein
Sven Hohenstein

Reputation: 81713

Here's an approach to find the column names of all columns that include at least one nonzero value.

tmp <- colSums(x != 0)
#  a  b  c  d  e  f  g  h 
#  0 12  0 11  0 12  0 11 

names(x)[as.logical(tmp)]
# [1] "b" "d" "f" "h"

Upvotes: 1

twin
twin

Reputation: 1669

names(x)[colSums(pmax(x != 0)) > 0]

Upvotes: 4

Related Questions