r - 将柱高转换为英寸 (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 |
我非常卡住,因为我很难将这些字符串变量转换为数值。请帮忙,谢谢
解决方案
这是一个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
推荐阅读
- python - 使用 biopython 重命名交错的 fastq 标头
- sql-server - 如何获取每个用户名的最后一条记录
- mongodb - Loopback 4/MongoDB - 外键未转换为 ObjectID
- php - 生成包含 2 个字母和 5 个数字的字母数字字符串。PHP
- javascript - 如何更改父元素的样式
React.js 中的标签? - xtext - 如何从 XExpression 获取 JvmModelInferrer 方法体并附加样板代码
- ruby-on-rails - ActiveStorage Rails 中的样式和验证,如 Paperclip
- sql-server - Docker ~ 在 microsoft/windowsservercore 上安装 SQL Express
- python - python3.0 的 concat() 备用组
- angular - 如何将动态 HTML 标记传递给引导模式?