基于指定列表文本批量重命名R语言数据框列名的需求
Replace Column Names in List of Data Frames with Corresponding Name Lists
To swap out the column names of each data frame in myTables with the matching name vector from myNames, you can use mapply() to iterate over both lists in parallel. Here's a clean, functional solution:
# Rename columns for every data frame in the list myTables_renamed <- mapply(function(df, name_vec) { colnames(df) <- name_vec df }, myTables, myNames, SIMPLIFY = FALSE)
Quick Breakdown:
mapply()pairs each data frame inmyTableswith its corresponding name list frommyNames- The anonymous function updates the column names of the data frame and returns the modified version
SIMPLIFY = FALSEensures the output stays as a list of data frames (instead of being coerced into a matrix)
Example: First Data Frame After Renaming
Here’s what the first data frame (myTables_renamed[[1]]) looks like with the column names from myNames[[1]]:
| 2019 | 2020 | 2021 | 2022 | 2023 | ||
|---|---|---|---|---|---|---|
| Ventas Cliente | 98716127 | 1477902 | 1970536 | 2955805 | 4433708 | |
| Revenue\n\200 | 987,161 | 1,477,902 | 1,970,536 | 2,955,805 | 4,433,708 | |
| Expenditure\n\200 | 890,623 | 1,337,031 | 1,732,873 | 2,569,122 | 3,829,434 | |
| Profit (Loss)\n\200 | 96,538 | 140,871 | 237,663 | 386,683 | 604,274 |
内容的提问来源于stack exchange,提问作者user8959427
相关产品推荐
相关产品推荐

