我正试着把一列脚转换成英寸。通常是简单的乘法,但当格式分别为(5-10)或(6-2)为70英寸和74英寸时,我对如何转换感到困惑。到目前为止这是我的密码。我想要改变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")发布于 2020-11-15 01:17:47
您可以将Ht列拆分为两个单独的列feet和inches,然后执行计算以计算身高。
library(dplyr)
library(tidyr)
combine.data %>%
separate(Ht,c('feet', 'inches'), sep = '-', convert = TRUE, remove = FALSE) %>%
mutate(feet = 12*feet + inches) %>%
select(-inches)发布于 2020-11-14 21:40:35
一个选项是在将conv_unit列转换为numeric后从measurements使用character
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 74https://stackoverflow.com/questions/64838855
复制相似问题