我想将列号添加到数据框中的列名称前面。这样做的最佳方法是什么?
例如,我想在下表中找到类似“1_mpg”,“2_cyl”的内容:
structure(list(mpg = c(21, 21), cyl = c(6, 6)), .Names = c("mpg",
"cyl"), row.names = c("Mazda RX4", "Mazda RX4 Wag"), class = "data.frame")
然后如何将其扩展到数据框列表?
list(structure(list(mpg = c(21, 21), cyl = c(6, 6)), .Names = c("mpg",
"cyl"), row.names = c("Mazda RX4", "Mazda RX4 Wag"), class = "data.frame"),
structure(list(mpg = c(21, 21), cyl = c(6, 6)), .Names = c("mpg",
"cyl"), row.names = c("Mazda RX4", "Mazda RX4 Wag"), class = "data.frame"))
答案 0 :(得分:0)
这是我最终使用的(尽管我猜测有更优雅的东西):
# sample list of 2 data frames
x =
list(structure(list(mpg = c(21, 21), cyl = c(6, 6)), .Names = c("mpg",
"cyl"), row.names = c("Mazda RX4", "Mazda RX4 Wag"), class = "data.frame"),
structure(list(mpg = c(21, 21), cyl = c(6, 6)), .Names = c("mpg",
"cyl"), row.names = c("Mazda RX4", "Mazda RX4 Wag"), class = "data.frame"))
# create function to append an index to column names
newColNames = function(a) {
b=lapply(seq_along(colnames(a)),
function(i) paste(i,"_",colnames(a)[i],sep=""))
colnames(a)=b
return(a)
}
# apply function
new_list = lapply(x, function(y) newColNames(y))