3

I have a huge list with data.frames (same number of columns, different number of rows). I succeeded to use apply - instead of the for loops I learned to avoid - to create a mean value over specific columns in each list element with

t2<-lapply(t1, function(x) cbind(x,rowMeans(x[,c("ColumnX","ColumnY","ColumnZ")])))

The problem I am stuck with now is the new columns name. It is "rowMeans(x[,c("ColumnX","ColumnY","ColumnZ")])".

How can I change this for all list elements? My poor "lapply"-knowledge was not sufficient for this task.

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
Jochen Döll
  • 383
  • 3
  • 11

2 Answers2

4

There's two ways to do this, and it actually has to do with the cbind function and not the lapply function:

cbind(x,DesiredName = rowMeans(x[,...]))

Or after you've cbind'ed:

> names(x)
[1] "Column X" "Column Y" "Column Z" "rowMeans(x[,...])"
> names(x)[4]
"rowMeans(x[,...])"
> names(x)[4] <- "DesiredName" ###Assign a name to the fourth column
> names(x)
[1] "Column X" "Column Y" "Column Z" "DesiredName"

That's obviously the long way, but it useful for if you forget to name something during the apply or cbind process.

Señor O
  • 17,049
  • 2
  • 45
  • 47
1

Just add a colname, for example RowMeans

t2 <-lapply(t1, function(x) cbind(x,RowMeans=rowMeans(x[,c("ColumnX","ColumnY","ColumnZ")])))

Actually you can accomplish your goal using this alternative:

lapply(t1, function(x) transform(x,RowMeans=rowMeans(x[,c("ColumnX","ColumnY","ColumnZ")])))

Here RowMeans is the name of the new variable containing each row mean.

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • I do not understand the `transform` and the last, shorter solution: The thing is, that I do not want to create rowMeans over the complete row, but only over three columns... which is accomplished by your first solution. Thank you for that. – Jochen Döll Oct 30 '12 at 08:59
  • @JochenDöll I was wrong, actually I thought your list consisted of only three cols, so the 2nd and 3rd solution did not work. I had to make some assumptions since you didn't provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). I've just edited my answer to take into account your desired output. If you want to get to know what `transform` does you have to make a little effort and read the help file by doing `?transform` – Jilber Urbina Oct 30 '12 at 11:12