0

I have a matrix as like this

structure(list(Item = structure(c(3L, 1L, 4L, 2L), .Label = c("boat", 
"bus ", "Car", "jeep"), class = "factor"), Cost = structure(c(3L, 
1L, 2L, 4L), .Label = c("E.02", "E0.23", "E2.03", "E5.60"), class = "factor"), 
BMW = c(0, 2.5, 12, 0.089), VW = c(0.56, 4.56, 0, 0.054), 
Bens = c(0.06, 5.01, 4.57, 0), Pet = c(0.02, 5.31, 0.36, 
45)), class = "data.frame", row.names = c(NA, -4L))

I need to remove columns which have zero. I tried with apply

   row_sub = apply(data, 1, function(row) all(row !=0 ))
   data[row_sub,]

But it is not working

Expected output

Item Cost BMW VW   Bens Pet
boat E.02 2.5 4.56 5.01 5.31 
user90
  • 381
  • 2
  • 10
  • 2
    Does this answer your question? [How to remove rows with any zero value](https://stackoverflow.com/questions/9977686/how-to-remove-rows-with-any-zero-value) – user438383 Oct 07 '20 at 11:07
  • Do you mean you want to remove rows which contain zero? Because your title says columns, but your expected output suggests you mean rows. – user438383 Oct 07 '20 at 11:08
  • 1
    `row_sub = apply(data!=0, 1, all)` – jogo Oct 07 '20 at 11:15

1 Answers1

1
df[df==0]<-NA
df<-na.omit(df)
df

Item Cost BMW   VW Bens  Pet
boat E.02 2.5 4.56 5.01 5.31
D.J
  • 1,180
  • 1
  • 8
  • 17