【问题标题】:Convert Column heights into inches (R)将柱高转换为英寸 (R)
【发布时间】:2021-10-11 02:41:06
【问题描述】:

我是初学者,我有这个高度为 (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

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

【问题讨论】:

  • 具体是什么意思,例如5'11"代表什么? 6.5.25" 的错字是什么?
  • 5'11" 代表 5 英尺 11 英寸高。6.5.25 中的拼写错误是在 6 之后应该是 ' 但有一个句点。该值应该读作 6'5.25"。另外,我是初学者,需要对代码进行彻底的解释。
  • 那么这里也有一个错字。 6'0.25

标签: r regex dataframe data-science


【解决方案1】:

一些数据插入错误使这比实际上更难

library(stringr)
library(dplyr)
df <- data.frame(x =c("5\'11\"","6'1\"","6.5.25\""),y = c("5\'10\"","6\'0.25","6\'4\"") )

correction <- function(str){
  output <- str_replace(str,"6\\.5\\.25\"","6\'5\\.25")
  # Corrects first typo
  output <- ifelse(str_detect(output,"\"$") == FALSE,str_replace(output,"$","\""),output)
  # Corrects second typo
  output <- 
    as.numeric(str_extract(output,"^.+(?=\')")) *12 +
    as.numeric(str_extract(output,"(?<=\').+(?=\"$)"))
  # Calculate inch
}               
                 
df %>%
  mutate(across(c(x,y),~ correction(.)))
#>       x     y
#> 1 71.00 70.00
#> 2 73.00 72.25
#> 3 77.25 76.00

reprex package (v2.0.0) 于 2021-08-06 创建

【讨论】:

    【解决方案2】:

    这是dplyrpurrr 的解决方案:

    测试数据已更新

    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
    

    【讨论】:

    • 我认为最后一行mutate行有错误,除了最后一行“mutate(across(everything(), ~ map_dbl(., function(x) as.numeric) (x)[1] * 12 + as.numeric(x)[2])))" --- 我收到一个错误:mutate() 输入问题..1..1 = across(...)。强制引入的 iNA
    • 这似乎唯一起作用的值是在第 2 列第 3 行。我认为是因为该值没有像数据框中的其他值一样在值之后有尾随 "。我需要从数据框中存在的每个值中删除尾随",然后我认为它会起作用。你能告诉我怎么做吗?
    • 只是为了确定:代码对我使用的测试数据有效吗?
    • 查看更新的答案。这现在有效吗?我意识到您可能没有' '(即2 个单引号),而是"(1 个双引号)。如果仍然存在问题,为什么不以可重现的格式发布您的数据??
    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2011-01-09
    相关资源
    最近更新 更多