R returns error when using apply to repeat a function on each row of a data frame

Viewed 16

I have a data frame named "Output":

head(Output)

X.110a.  X.110b.  X.110c. X.11a.  X.11b.  X.11c.  X.127a. X.127b. X.129a.  X.129b.
iNOS       0 4.945371 0.000000      0 0.00000 0.00000 0.000000       0       0 0.000000
TNF        0 0.000000 0.000000      0 4.38255 0.00000 2.780874       0       0 4.727186
IL6        0 0.000000 3.885568      0 4.38255 0.00000 0.000000       0       0 0.000000
IL10       0 0.000000 3.885568      0 4.38255 0.00000 2.780874       0       0 4.727186
ARG1       0 4.945371 0.000000      0 0.00000 2.07701 0.000000       0       0 0.000000
IL1B       0 0.000000 3.885568      0 4.38255 0.00000 2.780874       0       0 0.000000

This "Output" data frame consists of 643 rows (row.names = T (iNOS etc.)) and 127 columns (header = T (X.110a etc.)

I want to remove any 0 value cells from the data frame one row at a time:

iNOS <- Output[1,] %>% select_if(colSums(.) != 0)

iNOS

X.110b.  X.129c.  X.133b.  X.186a.  X.186b.  X.189a. X.190a.    X.1a.  X.211a.
iNOS 4.945371 4.945371 4.789241 5.950748 5.950748 3.805853  4.1198 3.987149 4.945371

The idea was to write this as a function and use apply() to apply the function to each row of the data frame individually before using rbind to reform the dataframe.

ScanHits <- function(x) {x[,] %>% select_if(colSums(.) != 0)}
apply(Output, 1, ScanHits)

However this always returns the following error message:

Error in x[, ] : incorrect number of dimensions

Is there some issue with my code, perhaps its related to the x[] in the function code? I'm quite new to R and don't completely understand the use of the apply() function when it comes to data frames.

Any help would be hugely appreciated!

1 Answers

IF we want to apply a function to non-zero elements in each row

apply(Output[-1], 1, function(x) yourfunction(x[x != 0]))
Related