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

如何用正则表达式在R中将height列转换为total_inches数值列?

解决方案

首先加载提供的数据集:

bball_data <- structure(list(name = c("Alaa Abdelnaby", "Zaid Abdul-Aziz",
"Kareem Abdul-Jabbar", "Mahmoud Abdul-Rauf", "Tariq Abdul-Wahad",
"Shareef Abdur-Rahim"),
year_start = c(1991L, 1969L, 1970L, 1991L,
1998L, 1997L),
year_end = c(1995L, 1978L, 1989L, 2001L, 2003L,
2008L),
position = c("F-C", "C-F", "C", "G", "F", "F"),
height = c("6-10",
"6-9", "7-2", "6-1", "6-6", "6-9"),
weight = c(240L, 235L, 225L,
162L, 223L, 225L),
birth_date = c("June 24, 1968", "April 7, 1946",
"April 16, 1947", "March 9, 1969", "November 3, 1974", "December 11, 1976"
),
college = c("Duke University", "Iowa State University", "University of California, Los Angeles",
"Louisiana State University", "San Jose State University", "University of California"
)),
row.names = c(NA, 6L), class = "data.frame")

方法1:拆分字符串直接计算

用str_split_fixed按分隔符"-"拆分height列,提取英尺和英寸数值后计算总英寸:

library(tidyverse)

bball_data <- bball_data %>%
  mutate(
    # 拆分出英尺和英寸
    feet = as.numeric(str_split_fixed(height, "-", 2)[,1]),
    inches = as.numeric(str_split_fixed(height, "-", 2)[,2]),
    # 计算总英寸
    total_inches = feet * 12 + inches
  ) %>%
  select(-feet, -inches) # 可选:删除中间临时列

方法2:正则捕获组提取数值计算

用正则一次性捕获英尺和英寸的数字组,避免重复操作,更高效:

library(tidyverse)

# 正则捕获两个数字组:(\\d+)-(\\d+)
height_nums <- str_match(bball_data$height, "(\\d+)-(\\d+)")

bball_data <- bball_data %>%
  mutate(
    total_inches = as.numeric(height_nums[,2]) * 12 + as.numeric(height_nums[,3])
  )

方法3:修复你用str_replace的思路

你之前替换得到的是字符串表达式(如"6*12+10"),需要将字符串转为可执行代码计算,注意仅在数据安全可控时使用:

library(tidyverse)

bball_data <- bball_data %>%
  mutate(
    # 替换为计算表达式字符串
    expr = str_replace(height, "(\\d+)-(\\d+)", "\\1*12+\\2"),
    # 执行表达式并转为数值
    total_inches = map_dbl(expr, ~eval(parse(text=.x)))
  ) %>%
  select(-expr) # 可选:删除中间临时列

验证结果

执行以下代码查看转换后的结果:

bball_data %>% select(name, height, total_inches)

输出结果:

name height total_inches
1       Alaa Abdelnaby   6-10           82
2      Zaid Abdul-Aziz    6-9           81
3  Kareem Abdul-Jabbar    7-2           86
4   Mahmoud Abdul-Rauf    6-1           73
5    Tariq Abdul-Wahad    6-6           78
6 Shareef Abdur-Rahim    6-9           81

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:20:31