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

David Winsemius dwinsemius at comcast.net
Fri Feb 19 08:00:14 CET 2010


On Feb 19, 2010, at 1:36 AM, 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 :)

It would not work if there were paired negative and positive values or  
any collection that summed to zero.

 > dataset1 <-
structure(list(sr_no = 1:4, var1 = c(5L, 3L, 4L, 11L), var2 = c(0,
0, 1, -1), var3 = c(3L, 2L, 4L, 1L), var4 = c(1L, 9L, 7L, 6L),
     var5 = c(0L, 0L, 0L, 0L)), .Names = c("sr_no", "var1", "var2",
"var3", "var4", "var5"), row.names = c(NA, -4L), class = "data.frame")

Perhaps:
 > idx <- vector()
 > for (x in seq_along(names(dataset1))) if (all(dataset1[, x] == 0))  
{ } else{ idx<- c(idx, x)}

 > dataset1[, idx]
   sr_no var1 var2 var3 var4
1     1    5    0    3    1
2     2    3    0    2    9
3     3    4    1    4    7
4     4   11   -1    1    6

Or a modification to Kimmo Elo's code which would still "break" if any  
columns were character:

 > subset(dataset1, select=which(colSums(abs(dataset1))!=0))
   sr_no var1 var2 var3 var4
1     1    5    0    3    1
2     2    3    0    2    9
3     3    4    1    4    7
4     4   11   -1    1    6

>
> HTH,
> Kimmo


--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT



More information about the R-help mailing list