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.
如果我想更改列表中数据框的名称(而不是父列表的名称),我无法通过names()或colnames()直接访问它们,而是必须使用lapply()来获取名称。
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.
但是,如果我使用lapply返回列名,那么它们只存在于lapply调用中,并且我无法在父环境中为列表分配新名称。
Here's a MWE below:
这是下面的MWE:
1/ Create the object
1 /创建对象
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
2 /无法直接访问数据框的列名
names(y)
NULL
空值
colnames(y)
NULL
空值
3/ We can try to use lapply
3 /我们可以尝试使用lapply
lapply(y, function(z) names(z) <- c('Op', 'Hi', 'Lo', 'Clo'))
[[1]]
[[1]]
[1] "Op" "Hi" "Lo" "Clo" ...
[1]“Op”“Hi”“Lo”“Clo”......
But it hasn't actually assigned names to the object.
但它实际上没有为对象分配名称。
1 个解决方案
#1
16
You can use setNames
...
你可以使用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.
这是一个便捷函数,用于设置对象上的名称并返回该对象。它在函数定义的最后是最有用的,其中一个是创建要返回的对象,并且不希望将它存储在名称下,以便可以分配名称。
#1
16
You can use setNames
...
你可以使用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.
这是一个便捷函数,用于设置对象上的名称并返回该对象。它在函数定义的最后是最有用的,其中一个是创建要返回的对象,并且不希望将它存储在名称下,以便可以分配名称。