2

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=".")})
BAMF4bacon
  • 523
  • 1
  • 7
  • 21
  • 2
    You seem to just want `do.call(paste, c(df[1:3], sep = "."))`. And you shouldn't try to use `apply()` on data frames. It is for matrices, and using it on data frames will yield unintended results almost all the time. – Rich Scriven Jun 02 '16 at 19:31
  • Richard, this is a good approach, but I think do.call parsers over members of the list, which in this case are the columns. Can this be modified to do this operating row by row? – BAMF4bacon Jun 02 '16 at 20:09
  • @RichScriven what's the best alternative? – 3pitt Mar 01 '18 at 15:17

2 Answers2

1

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)
sync11
  • 1,224
  • 2
  • 10
  • 23
0

First, please note this is not a problem for columns. lapply will do columns without trouble

colnames(df) <- lapply(df[1:3,], function(x) {paste(x,sep=".")})

A great answer by rsoren is found here). Modified for this problem:

for (row in 1:nrow(df)) { 
    rownames(df)[row] <- paste(df[row,1:3],sep=".") 
}

You can't do rows with lapply. Here is an alternate, more intuitive approach. To operate on rows, we make the transpose first; now the rows are columns and lapply can operate on the columns.

tdf<-as.data.frame(t(df))
rownames(df) <- lapply(tdf[1:3,], function(x) {paste(x,sep=".")})

The only downside to this is that R makes a copy of the table during the transpose, so it doubles memory usage. However, rsoren's method does not.

Now I can delete the extra rows and columns and make the matrix I want with proper row and column names.

myMatrix <- as.matrix(df[-(1:3),-(1:3)])
Community
  • 1
  • 1
BAMF4bacon
  • 523
  • 1
  • 7
  • 21
  • (deleted answer to deleted comment) – BAMF4bacon Jun 02 '16 at 19:47
  • 1
    Careful. Transposing a data frame is generally a bad idea - this will not preserve the class of the original data. Furthermore, you can easily use `lapply()` to index the rows. For example something like this: `lapply(1:3, function(i){ paste(df[i, 1:3], sep = ".") } )` – Andrie Jun 02 '16 at 20:40