R语言中无法将原float类型变量转为double类型的求助
Hey there! Sounds like you’re stuck on converting those percentage columns to double type—let’s break this down and get it sorted.
The Root Issue
The reason setting col_types = cols() to float or double isn’t working is almost certainly because your percentage columns have non-numeric characters (like the % symbol) in them. Readr can’t parse those into numeric types directly, which is why only character works.
Step-by-Step Solution
Here’s how to fix this, using tidyverse tools since they’re great for data cleaning:
First, read the column as character (you already know this works, so stick with it for now):
library(readr) library(stringr) df <- read_csv("your_dataset.csv", col_types = cols( your_percent_column = col_character() ))Clean the percentage symbol and convert to double
You have two easy ways to do this:- Use
str_remove()to strip the%then convert withas.numeric()(which gives you double-precision numbers in R):df_cleaned <- df %>% mutate(your_percent_column = str_remove(your_percent_column, "%") %>% as.numeric()) - Or use
parse_number()from readr—it automatically extracts numeric values from strings, ignoring non-numeric characters like%:df_cleaned <- df %>% mutate(your_percent_column = parse_number(your_percent_column))
- Use
Handle edge cases (if needed)
If your data has other weird characters (like spaces, commas for thousands separators), expand the cleaning step:df_cleaned <- df %>% mutate(your_percent_column = str_remove_all(your_percent_column, "[%, ]") %>% as.numeric())
Bonus: Do It All in One Step
You can even combine reading and cleaning into a single pipe to keep your code clean:
df_cleaned <- read_csv("your_dataset.csv", col_types = cols(your_percent_column = col_character())) %>% mutate(your_percent_column = parse_number(your_percent_column))
Once you’ve done this, your column will be a double type, ready for any percentage calculations you need to run!
内容的提问来源于stack exchange,提问作者Reeza

