重命名列表中Data.frame的列 [英] Rename Columns of Data.frame in list
问题描述
我正在尝试使用lapply(并希望使用lapply的解决方案)来重命名位于列表中的data.frame的列,但它返回的是名称,而不是重命名的data.frames:
I am trying to use lapply (and want the solution with lapply) to rename columns of a data.frame located in a list, but it's returning names, not the renamed data.frames:
# define list
li <- list(u_n = data.frame(x = 1:3), r_l = data.frame(y = 4:6))
# trying to rename columns after the element of the list they're located in
li_2 <- lapply(1:length(li),
function(x,y) colnames(y[[x]]) <- names(y)[x], y = li)
但是,这返回:
[[1]]
[1] "u_n"
[[2]]
[1] "r_l"
如果我使用与lapply中分别指定的函数相同的方法,则它确实可以工作:
If I use the same method as the function specified in lapply individually, it does work:
li[1]
$u_n
x
1 1
2 2
3 3
colnames(li[[1]]) <- names(li)[1]
li[1]
$u_n
u_n
1 1
2 2
3 3
推荐答案
在命名该对象后,我们可能需要返回该对象.
We may need to return the object after naming it.
li_2 <- lapply(seq_along(li), function(i) {
colnames(li[[i]]) <- names(li)[i]
li[[i]]})
或者这可以通过setNames
li_2 <- lapply(names(li), function(x) setNames(li[[x]], x) )
或者我们可以使用Map
,它是mapply
的包装(这是sapply
的多元版本).我们将FUN
应用于每个输入的相应元素.
Or we could use Map
, which is a wrapper for mapply
(that is a multivariate version of sapply
). We apply the FUN
to corresponding elements of each input.
li_2 <- Map(setNames, li, names(li))
在这里,我们将每个list
元素的列名更改为list
元素的对应名称.如果我们使用匿名函数,它将是
Here, we are changing the column names of each list
element with corresponding names of the list
element. If we are using anonymous function, it would be
Map(function(x,y) setNames(x,y), li, names(li))
这篇关于重命名列表中Data.frame的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!