Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign column names to list of dataframes

Tags:

r

I have a list of dataframes, whose columns have names.

If I want to change the names of the dataframes within the list (rather than the names of the parent list), I cannot access them directly via names() or colnames(), rather I must use lapply() to get the names.

However, if I use lapply to return the column names, then they only exist within the lapply call, and I cannot assign new names to the list in the parent environment.

Here's a MWE below:

1/ Create the object

require(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
y <- lapply(split(x, "months"), data.frame)

2/ The column names of the dataframes are not directly accessible

names(y)

NULL

colnames(y)

NULL

3/ We can try to use lapply

lapply(y, function(z) names(z) <- c('Op', 'Hi', 'Lo', 'Clo'))

[[1]]

[1] "Op" "Hi" "Lo" "Clo" ...

But it hasn't actually assigned names to the object.

like image 356
lilster Avatar asked Nov 13 '13 00:11

lilster


1 Answers

You can use setNames...

lapply( y , setNames , nm = c('Op', 'Hi', 'Lo', 'Clo') )
#[[1]]
#                 Op       Hi       Lo      Clo
#2007-01-02 50.03978 50.11778 49.95041 50.11778
#2007-01-03 50.23050 50.42188 50.23050 50.39767
#2007-01-04 50.42096 50.42096 50.26414 50.33236
#       ...      ...      ...      ...      ...

Quoting directly from the help page:

This is a convenience function that sets the names on an object and returns the object. It is most useful at the end of a function definition where one is creating the object to be returned and would prefer not to store it under a name just so the names can be assigned.

like image 112
Simon O'Hanlon Avatar answered Oct 22 '22 07:10

Simon O'Hanlon