首页 > 解决方案 > 将柱高转换为英寸 (R)

问题描述

我是初学者,我有这个高度为(x ft' y 英寸)的数据框我需要将此值转换为以英寸为单位的高度的单个数字

height_w_shoes height_wo_shoes
5'11" 5'10"
6'1" 6'0.25
6.5.25" 6'4"

我需要修复“height_w_shoes”列的最后一行中的错字(或者可能不是,取决于解决方案,当它应该是“'”时,当前是“.”),然后将这些测量值转换为英寸:

height_w_shoes height_wo_shoes
71 70
73 72.25
77.25 76

我非常卡住,因为我很难将这些字符串变量转换为数值。请帮忙,谢谢

标签: rregexdataframedata-science

解决方案


这是一个dplyr解决purrr方案:

测试数据更新

df <- data.frame(
  h1 = c("6.5.25", "5'11\"", "6'11\"", "6'0.25"),
  h2 = c("66.4.2", "7'10\"", "16'11\"", "7'2.50"),
  h3 = c("4'4.2", "7'10\"", "16'11\"", "7.7.77")
)

解决方案更新

library(dplyr)
library(purrr)
 df %>%
   # Step 1: correct typo:
   mutate(across(c(everything()), 
                ~ sub("(?<=^\\d{1}|^\\d{2})\\.", "'", ., perl = T))) %>%
   # Step 2: remove trailing `"`:
   mutate(across(c(everything()), 
                ~ gsub('"$', "", .))) %>%
   # Step 3: split strings on `'`:
   mutate(across(c(everything()), 
                ~ strsplit(.,"'"))) %>%
   # Step 4: convert to numeric and perform calculation:
   mutate(across(everything(), 
                 ~ map_dbl(., function(x) as.numeric(x)[1] * 12 + as.numeric(x)[2])))
     h1    h2     h3
1 77.25 796.2  52.20
2 71.00  94.0  94.00
3 83.00 203.0 203.00
4 72.25  86.5  91.77

推荐阅读