Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

r - Rename Columns of Data.frame in list

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)

However, this returns:

[[1]]
[1] "u_n"

[[2]]
[1] "r_l"

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]]})

Or this can be done with setNames

 li_2 <- lapply(names(li), function(x) setNames(li[[x]], x) )

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))

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...