Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing column names in list elements

Tags:

r

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.

like image 900
Jochen Döll Avatar asked May 11 '26 09:05

Jochen Döll


2 Answers

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.

like image 65
Señor O Avatar answered May 14 '26 03:05

Señor O


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.

like image 24
Jilber Urbina Avatar answered May 14 '26 03:05

Jilber Urbina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!