R语言:如何将含lakhs、Cr单位的字符向量转换为数值?
Convert Indian Number Units to Numeric Values in R
No problem, here are two straightforward approaches to convert your character vector into the correct numeric values based on the unit conversions you specified (lakhs = 100000, Cr = 10000000):
Option 1: Base R (No Extra Packages Needed)
This method uses basic string manipulation functions built into R, so you don't need to install any additional packages:
# Your original character vector x <- c("2.0 lakhs","22.0 lakhs","1.6 Cr", "1.8 Cr") # Step 1: Extract the numeric part from each string numeric_part <- as.numeric(sub("[^0-9.]", "", x)) # Step 2: Extract the unit part (remove numbers, decimals, and spaces) unit_part <- trimws(sub("[0-9.]", "", x)) # Step 3: Map units to their respective multipliers multiplier <- ifelse(unit_part == "lakhs", 100000, 10000000) # Step 4: Calculate the final numeric values converted_values <- numeric_part * multiplier # Check the result converted_values # Output: [1] 200000 2200000 16000000 18000000
How this works:
sub("[^0-9.]", "", x)removes all characters that aren't numbers or decimals, leaving just the numeric portion.trimws(sub("[0-9.]", "", x))removes numbers/decimals, then trims any leftover whitespace to get clean unit names.ifelse()assigns the correct multiplier based on the unit, then we multiply the numeric part by this multiplier to get the final value.
Option 2: Tidyverse Approach (More Readable)
If you're already using the tidyverse suite of packages, this method is more intuitive and easier to extend if you add more units later:
First, make sure you have the tidyverse installed (if not, run install.packages("tidyverse")):
library(tidyverse) x <- c("2.0 lakhs","22.0 lakhs","1.6 Cr", "1.8 Cr") converted_values <- tibble(original = x) %>% mutate( # Extract numeric part directly with parse_number() num = parse_number(original), # Remove numbers/decimals/spaces to get the unit unit = str_remove_all(original, "[0-9. ]"), # Map units to multipliers with case_when() multiplier = case_when( unit == "lakhs" ~ 1e5, # 1e5 is shorthand for 100000 unit == "Cr" ~ 1e7 # 1e7 is shorthand for 10000000 ), # Calculate final value final_value = num * multiplier ) %>% # Pull just the final numeric vector if needed pull(final_value) converted_values # Output: [1] 200000 2200000 16000000 18000000
Why this is useful:
parse_number()is a handy function that automatically extracts numeric values from strings, even with extra characters.case_when()makes it simple to add more unit conversions later (e.g., if you need to handle "Thousands" or "Million" down the line).
Either approach will give you the correct converted numeric values!
内容的提问来源于stack exchange,提问作者siddhartha medharametla
相关产品推荐
相关产品推荐

