根据R中列表的名称重命名数据框的列 [英] Rename Columns of dataframe based on names of list in R
本文介绍了根据R中列表的名称重命名数据框的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个列表对象中保存了多个数据框.它们共享相同的两个列名.我想将第二列重命名为数据框的名称.
I have multiple dataframes saved in a list object. They share the same two column names. I'd like to rename the second column to the name of the dataframe.
示例数据:
df1 <- data.frame(A = 1:10, B= 11:20)
df2 <- data.frame(A = 21:30, B = 31:40)
df3 <- data.frame(A = 31:40, B= 41:50)
df4 <- data.frame(A = 51:80, B = 61:70)
listDF <- list(df1, df2,df3, df4)
我正在尝试使用lapply重命名第二列以匹配数据框的名称.
I'm trying to use lapply to rename the second column to match the name of the dataframe.
# trying to rename second column after the element of the list they're located in
listDF_2 <- lapply(names(listDF), function(x) setNames(listDF[[x]], x) )
推荐答案
要跟踪名称,可以使用:
To keep track of names, you can use:
listDF <- list(df1 = df1, df2 = df2, df3 = df3, df4 = df4)
然后您可以使用for循环:
Then you can use for loop:
for (i in names(listDF)){
colnames(listDF[[i]]) <- c("A", i)
}
或者如果您需要使用lapply,则可以使用以下方法:
Or if you need to use lapply, you may use this:
newDF <- lapply(names(listDF), function(x){
colnames(listDF[[x]]) <- c("A", x)
listDF[[x]]
})
names(newDF) <- names(listDF)
这篇关于根据R中列表的名称重命名数据框的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文