Jochen Döll
Jochen Döll

Reputation: 383

Changing column names in list elements

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.

Upvotes: 3

Views: 8188

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61214

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.

Upvotes: 1

Se&#241;or O
Se&#241;or O

Reputation: 17432

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.

Upvotes: 4

Related Questions