R语言数据框变量名未转小写改下划线但控制台显示正常问题
Ah, I’ve run into this exact quirk before! Let’s break down what’s going on and get your column names updated properly.
From what you’ve described: you ran these two lines to rename your film data frame’s columns, the console output of names(film) looks correct, but the actual displayed column names in your data frame don’t match the lowercase/underscore format you want. Here’s how to fix that:
1. Combine your renaming steps into a single assignment
Splitting the rename into two separate lines can sometimes lead to unexpected behavior (like accidentally overwriting the name reference mid-process). Try merging the gsub and tolower operations into one line to ensure all changes apply at once:
names(film) <- tolower(gsub(' ', '_', names(film)))
This first replaces all spaces with underscores, then converts every character to lowercase—all in one go, so there’s no chance of a half-updated state.
2. Confirm you’re modifying the right film object
Double-check that you’re working with the correct data frame in your global environment. Sometimes if you’re inside a function or have multiple objects named film, you might be modifying a copy instead of the one you’re viewing. Run these lines right after renaming to verify:
names(film) <- tolower(gsub(' ', '_', names(film))) # Immediately check the result names(film)
If this prints your desired column names but you still see old names in RStudio’s Environment pane, click the Refresh button in the Environment tab—it doesn’t always update automatically when you modify objects.
3. Use the tidyverse for a more intuitive workflow (optional)
If you’re comfortable with the tidyverse, the rename_all function from dplyr makes this kind of renaming super straightforward and explicit:
library(dplyr) film <- film %>% rename_all(~ tolower(gsub(' ', '_', .x)))
This code explicitly reassigns the modified data frame back to film, so there’s no ambiguity about which object you’re updating.
Quick way to confirm it worked
After running your renaming code, test accessing one of the new column names—if it returns data instead of an error, the renaming was successful:
# Replace with your new column name head(film$worldwidebox_office)
内容的提问来源于stack exchange,提问作者Vivica

