9

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.

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, never seen that function before.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.