You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将英尺英寸格式的身高字符向量转换为厘米?

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 mutate step with str_replace to standardize the strings before extraction/splitting.
  • Use replace_na if you have missing values to avoid calculation errors.

内容的提问来源于stack exchange,提问作者SteveS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:23:02