[R] Deleting colmuns with 0's and also writing multple csv files

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Feb 19 08:42:43 CET 2010

(Forgot to cc. reply to K. Elo, apologies if you get it twice)

K. Elo wrote:
> Dear Anna,
> 19.02.2010 08:17, Anna Carter wrote:
>> (1) If the dataset contains some variables having all the entries = 0
>> and while analysing I want to delete those pericular columns, how do
>> acheive this. i.e.
> Let's suppose 'df' is your data frame, then:
> subset(df, select=which(colSums(df)!=0))
> should do the work :)

Beware negative entries in df! which(colSums(df!=0)) may work better,
but it is a bit "sneaky".

I'd also avoid subset in favour of df[....] or  df[,....]. And why use
indexing with which() when you can use the logical index directly?

My preference goes to df[,apply(df,2,any)] (a student assistant once
almost killed me when I showed her that after she had spent days
programming the same thing using loops and whatnots...)

    O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
   c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
  (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907

More information about the R-help mailing list