如何将英尺英寸格式的身高字符向量转换为厘米?
Convert Feet-Inch Height Strings to Centimeters in R
Got it, let's tackle this height conversion problem step by step. Since you're working with a tibble, we'll focus on tidyverse-based solutions that play nicely with your data structure.
Method 1: Split and Calculate with separate()
This approach breaks down the height string into separate feet and inches columns, cleans up the values, then computes the centimeter equivalent:
library(tidyverse) # Your original tibble height_data <- tibble(H = c("6'2\"", "5'10\"", "5'5\"", "5'1\"", "5'5\"", "5'4\"")) # Convert to centimeters height_cm <- height_data %>% # Split the string at the apostrophe, convert columns to numeric automatically separate(H, into = c("feet", "inches"), sep = "'", convert = TRUE) %>% # Remove the double quote from the inches column mutate(inches = as.numeric(str_remove(inches, "\""))) %>% # Calculate total centimeters: 1ft = 30.48cm, 1in = 2.54cm mutate(height_cm = feet * 30.48 + inches * 2.54) %>% # Keep original height string and the new centimeter column select(H, height_cm) # View the result height_cm
Method 2: Extract Directly with Regular Expressions
If you prefer a more concise approach without splitting columns, use regex to pull the numeric values directly from the string:
height_data %>% mutate( # Extract feet: match one or more digits at the start of the string feet = as.numeric(str_extract(H, "^\\d+")), # Extract inches: match digits between the apostrophe and double quote inches = as.numeric(str_extract(H, "(?<=')\\d+(?=\")")), # Compute centimeters height_cm = feet * 30.48 + inches * 2.54 ) %>% select(H, height_cm)
Quick Notes
- Both methods will give you the same result: for example,
6'2"converts to 187.96 cm,5'10"converts to 177.8 cm. - If your data has inconsistent formatting (like missing quotes or different separators), add a
mutatestep withstr_replaceto standardize the strings before extraction/splitting. - Use
replace_naif you have missing values to avoid calculation errors.
内容的提问来源于stack exchange,提问作者SteveS
相关产品推荐
相关产品推荐

