I am reading a CSV into R, where several columns contain percentages that are formatted as text strings with a percentage symbol at the end, e.g. "35%". readr::read_csv() interprets these as character-type data, but I want the data to be numeric so I can perform analysis.
The following code achieves this, but seems like a lot of "hoops" to jump through. Is there a standard function (or option for a function) that does the same thing? There doesn't seem to be a relevant option in the read_csv() function.
convert_percentage_string <- function(percentage_string) {
percentage_string %>%
stringr::str_extract(., "[0-9]+") %>%
as.numeric()
}
read_csv("my_data.csv") %>%
mutate_at(columns_with_percentages, convert_percentage_string)
Sample data:
tribble(~name, ~count, ~percentage,
"Alice", 4, "40%",
"Bob", 10, "65%",
"Carol", 15, "15%")
Expected result:
tribble(~name, ~count, ~percentage,
"Alice", 4, 40,
"Bob", 10, 65,
"Carol", 15, 15)
question from:
https://stackoverflow.com/questions/65600364/reading-x-formatted-percentages-into-r 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…