如何在R语言中将字符型阿拉伯/波斯数字转换为英文数值?
Got it, let's break this down for you! You've got a data frame where the first column holds Arabic or Persian numerals stored as character strings, and you need to turn those into standard numeric values so you can run calculations. Here are two reliable ways to do this in R:
1. Manual Mapping with String Replacement
First, let's start with a sample data frame to replicate your scenario:
# Create a sample data frame with Persian numerals as characters df <- data.frame( persian_nums = c("۰", "۱", "۲", "۳", "۱۲۳", "۴۵۶"), other_data = letters[1:6], stringsAsFactors = FALSE )
Next, we'll define a mapping between Persian/Arabic numeral characters and their standard numeric equivalents, then use string replacement to swap them out:
# Load the stringr package for easy replacement library(stringr) # Define the mapping from Persian numerals to standard digits persian_to_digit <- c( "۰" = "0", "۱" = "1", "۲" = "2", "۳" = "3", "۴" = "4", "۵" = "5", "۶" = "6", "۷" = "7", "۸" = "8", "۹" = "9" ) # Replace each Persian numeral character with the standard digit df$converted_nums <- str_replace_all(df$persian_nums, persian_to_digit) # Convert the resulting string to numeric type df$converted_nums <- as.numeric(df$converted_nums)
Now you can use df$converted_nums for any arithmetic operations—sum, mean, etc.—just like regular numbers!
2. Use the stringi Package for Simplified Conversion
If you prefer a more streamlined approach, the stringi package is built for handling multilingual text, including numeral conversions:
# Install and load stringi if you haven't already # install.packages("stringi") library(stringi) # Convert Persian/Arabic numerals directly to standard numeric values df$converted_nums <- as.numeric(stri_trans_general(df$persian_nums, "Any-Latin; Latin-ASCII"))
This function automatically handles the numeral conversion without needing a manual mapping—super handy!
Quick Notes
- If you run into
NAvalues after conversion, check for non-numeric characters in your original column (like symbols or letters). Usewarnings()to see which entries failed to convert. - Double-check that your input characters are indeed standard Persian/Arabic numerals (use
charToRaw(df$persian_nums[1])to verify their Unicode encoding if you're unsure).
内容的提问来源于stack exchange,提问作者mjoudy

