In R, how do I use apply() with data frames?

12,225

You can exclude the non-numeric columns/rows and deploy apply function onto the numeric rows.

Consider an example: If a data frame has 4 columns out of which the first one belongs to the character class, then use below code:

apply(Data.df[,2:4],2,func_name)
Share:
12,225
BAMF4bacon
Author by

BAMF4bacon

Updated on June 04, 2022

Comments

  • BAMF4bacon
    BAMF4bacon almost 2 years

    apply() allows you to select whether rows or columns with MARGIN=1 or MARGIN=2, respectively.

    But apply only works on matrices.

    For example, I have three rows of header information and 3 columns of descriptive information. I need to combine these into row names and row names and column names, respectively. So I can't easily use read.table() and skip the first 3 rows, and then delete the first 3 columns to get my matrix right away.

    This doesn't work on data frames, just matrices

    rownames(df)<-apply(df[,1:3], MARGIN=1,FUN=function(x){paste(x,sep=".")})