【问题标题】:Convert Height from Ft (6-1) to Inches (73) in R在 R 中将高度从英尺 (6-1) 转换为英寸 (73)
【发布时间】:2021-02-26 12:29:28
【问题描述】:

我正在尝试将一列英尺转换为英寸。通常它是简单的乘法,但是当格式分别为 70 和 74 英寸的 (5-10) 或 (6-2) 时,我对如何转换感到困惑。到目前为止,这是我的代码。我正在尝试更改combine.data$Ht

library(rvest)
library(magrittr)
library(dplyr)
library(purrr)

years <- 2010:2020

urls <- paste0(
  'https://www.pro-football-reference.com/draft/',
  years,
  '-combine.htm')

combine.data <- map(
  urls,
  ~read_html(.x) %>% 
    html_nodes(".stats_table") %>% 
    html_table() %>% 
    as.data.frame()
) %>%
  set_names(years) %>% 
  bind_rows(.id = "year") %>% 
  filter(Pos == 'CB' | Pos == "S")

【问题讨论】:

    标签: r dataframe web-scraping type-conversion


    【解决方案1】:

    您可以将Ht 列拆分为两个单独的列feetinches,然后执行计算以英尺为单位计算高度。

    library(dplyr)
    library(tidyr)
    
    combine.data %>%
      separate(Ht,c('feet', 'inches'), sep = '-', convert = TRUE, remove = FALSE) %>%
      mutate(feet = 12*feet + inches) %>%
      select(-inches)
    

    【讨论】:

      【解决方案2】:

      一个选项是在将character 列转换为numeric 之后使用measurements 中的conv_unit

      library(measurements)
      f1 <- function(x) {
              x1 <- as.numeric(sub("-.*", "", x))
              x2 <- as.numeric(sub(".*-", "", x))
              conv_unit(x1, "ft", "inch") + x2
       }
        
      combine.data$Ht <- f1(combine.data$Ht)
      head(combine.data$Ht)
      #[1] 69 71 72 71 69 74
      f1('5-11')
      #[1] 71
      
                   
      

      或者只使用base R

      f1 <- function(x) {
              x1 <- as.numeric(sub("-.*", "", x))
              x2 <- as.numeric(sub(".*-", "", x))
              (x1 * 12) + x2
       }
      combine.data$Ht <- f1(combine.data$Ht)
      head(combine.data$Ht)
      #[1] 69 71 72 71 69 74
      

      【讨论】:

      • 这适用于像 6-0 这样的数字,但不适用于像 5-11 这样的数字。例如,5-11 岁的球员应该是 71 英寸而不是 61.32 英寸。有什么建议吗?
      • @njmcd 请检查更新。它现在应该可以工作了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 2011-01-09
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2016-02-02
      相关资源
      最近更新 更多