Q:

Select columns based on sum

I have a data frame with many columns of genes and rows, for example
id  treatment time gene1 gene2 gene3 …
1      A       1     2     0    2    …
2      A       2     0     0    3    …
3      A       3     0     0    4    …
4      B       4     0     0    0    …
5      B       5     0     0    2    …
6      B       3     1     0    1    …
7      C       5     0     0    2    …

I would like to keep the all the first several columns (in the example data is three, but there are many columns in real data) and the genes columns that the column sum is > 0.
I would appreciate any help on my question. Thank you very much!

A:

I'm not entirely sure on whether you want to retain rows or columns with the sum of entries > 0.
In case of the former, you can use rowSums like this
df[rowSums(df[, grep("gene", names(df))]) > 0, ]
#id treatment time gene1 gene2 gene3
#1  1         A    1     2     0     2
#2  2         A    2     0     0     3
#3  3         A    3     0     0     4
#5  5         B    5     0     0     2
#6  6         B    3     1     0     1
#7  7         C    5     0     0     2

Or to retain only those columns with the sum of entries > 0 you can use colSums
df[, names(df) %in% c(
    names(df)[grep("gene", names(df), invert = T)],
    names(which(colSums(df[, grep("gene", names(df))]) > 0)))]
#  id treatment time gene1 gene3
#1  1         A    1     2     2
#2  2         A    2     0     3
#3  3         A    3     0     4
#4  4         B    4     0     0
#5  5         B    5     0     2
#6  6         B    3     1     1
#7  7         C    5     0     2

This assumes that all gene columns contain the word "gene" (and all non-gene columns do not contain the word "gene").
Or more concise (thanks @Shree), 
df[, c(rep(T, 3), colSums(df[, -c(1:3)]) > 0)]

which assumes that the first 3 columns are non-gene columns (and the remaining columns are all gene columns).

Sample data
df <- read.table(text =
    "id  treatment   time    gene1   gene2   gene3
1   A   1   2   0   2
2   A   2   0   0   3
3   A   3   0   0   4
4   B   4   0   0   0
5   B   5   0   0   2
6   B   3   1   0   1
7   C   5   0   0   2", header = T)

