Some times, simple questions seem to be difficult and solutions seem to be drowned in complex questions and their complex solutions. One of the simple question I came across recently was how to compare all the values in each column (except one) against a single column values. Requirement is to print and concatenate the column names instead of row values or status of comparison (True/False). Let us look at the following simple example:
===========================================
Gene, value1, value2, value3, Ave.value
A, 11, 12, 15, 11
B, 11, 12, 12, 12
C, 11, 19, 18, 14
=============================================
Now the question is to compare value1, value2 and value 3 against average value, print column names wherever values are bigger than average value (Ave.value here). For eg. if column value2 has value more than average value, print column name in that row (in a new column). Follow the code for better understanding.
code:
=============================================
df$new = apply(df[, 2:4] > df[, 5], 1, function(x)
    ifelse(any(x), paste(colnames(df)[2:4][x], collapse = ', '), ""))
=============================================
output:
=============================================
> df
  Gene value1 value2 value3 Ave.value            new
1    A     11       12     15        11                    value2, value3
2    B     11       12     13        12                    value3
3    C     11       19     18        14                    value2, value3
=============================================
Now if we want to compare all columns against a cut off (value of 14 in example), one can use following code:
Code:
==========================================
df$new=apply(df[,2:4],1,function(x) names(df[,2:4])[which(x>14)])
==========================================
output:
===========================================
> df
  Gene value1 value2 value3 Ave.value            new
1    A     11     12     15        11                       value3
2    B     11     12     13        12              
3    C     11     19     18        14                      value2, value3
==========================================