Apply/lapply function to all columns in matrix

Viewed 209

I have a matrix called seq$num, consisting of 100 columns and 30k rows. Each column corresponds to the name of a specific sample (es. CAGTCA), and every row is about a numeric value. With this type of object, I can access the first row writing seq$num[[1]] and so on for the other rows. This is a brief example of my database:

CAGTCA AGATCA GCTCGA GCTCGA
-0.4930 -2.0330 0.7100 0.1560
1.0030 0.0120 -1.0433 0.6701
0.0013 1.0013 1.2451 -1.3421

I would like to loop through all the samples using the lapply function and for each sample classify:

  • the numbers above 1.5 as "high".
  • the numbers below 0 as "low".
  • the numbers between 0 and 1.5 as "medium".

Then I need also to take note of how many high, low and medium numbers have a sample.

How can this be done? I've tried applying the lapply function, but I don't get the output I want.

1 Answers

You can write a function which divides data into categories.

classify <- function(x) ifelse(x >= 1.5, 'high', ifelse(x < 0, 'low', 'medium'))

For each dataframe in seq$num apply the classify function to it and use table to count.

res <- lapply(seq$num, function(x) table(classify(as.matrix(x))))
Related