如何在R语言中使用mutate函数?——创建export_ratio列时的报错求助
Hey there! That error pops up because either your exports or gdp column isn't stored as a numeric type in the eu_macro data frame. R can't perform division on non-numeric values (like character strings or factors), which is why the mutate step fails when calculating export_ratio.
Step 1: Verify the Data Types of Your Columns
First, let's confirm what type of data is in exports and gdp. Run this code to check the structure of your data frame:
str(eu_macro) # Or if you're using dplyr: library(dplyr) glimpse(eu_macro)
Look for the entries next to exports and gdp—they should say num (numeric) or dbl (double). If they say chr (character) or fct (factor), that's the root issue.
Step 2: Convert Columns to Numeric
If either column is non-numeric, convert them before calculating the ratio. Here are two common scenarios:
Scenario 1: Columns are stored as factors
If exports or gdp are factors, convert them to characters first, then to numeric:
eu_macro_fixed <- eu_macro %>% mutate( exports = as.numeric(as.character(exports)), gdp = as.numeric(as.character(gdp)), export_ratio = (exports/gdp)*100 ) %>% filter(year > 1995) %>% filter(country %in% c("Germany", "France", "Spain", "Sweden")) # Now plot ggplot(eu_macro_fixed, aes(year, export_ratio)) + geom_line(aes(color = country))
Scenario 2: Columns have non-numeric characters (like currency symbols or commas)
If your columns have extra characters (e.g., "$1000" or "1,000"), remove those first before converting:
eu_macro_fixed <- eu_macro %>% mutate( # Remove any non-numeric characters except dots (for decimals) exports = as.numeric(gsub("[^0-9.]", "", exports)), gdp = as.numeric(gsub("[^0-9.]", "", gdp)), export_ratio = (exports/gdp)*100 ) %>% filter(year > 1995) %>% filter(country %in% c("Germany", "France", "Spain", "Sweden")) # Plot the results ggplot(eu_macro_fixed, aes(year, export_ratio)) + geom_line(aes(color = country))
Step 3: Handle Missing Values (If Needed)
After conversion, you might get NA values if some entries couldn't be converted to numeric. You can either remove rows with NAs using na.omit() or handle them explicitly:
eu_macro_fixed <- eu_macro %>% mutate( exports = as.numeric(as.character(exports)), gdp = as.numeric(as.character(gdp)), export_ratio = (exports/gdp)*100 ) %>% filter(year > 1995) %>% filter(country %in% c("Germany", "France", "Spain", "Sweden")) %>% na.omit() # Remove rows with NA values
Once you've fixed the data types, your original plotting code should work without issues!
内容的提问来源于stack exchange,提问作者Shubham Patil

