gpt4 book ai didi

r - 将以英寸为单位的高度字符向量转换为厘米?

转载 作者:行者123 更新时间:2023-12-02 06:47:20 25 4
gpt4 key购买 nike

我得到一个字符向量:

tibble(H = c("6'2\"", "5'10\"", "5'5\"", "5'1\"", "5'5\"", "5'4\""))

我想把它转换成厘米。

请告知我该怎么做?

最佳答案

有几种方法可以使用

1) 粘贴成单个字符串后用 fread 读取

library(data.table)
fread(paste(sub('"', "", df1$H), collapse="\n"), sep="'")[,
as.matrix(.SD) %*% c(30.48, 2.54)][,1]
#[1] 187.96 177.80 165.10 154.94 165.10 162.56

2) 使用 gsubfn

library(gsubfn)
as.numeric(gsubfn("(\\d)'(\\d+)", ~ as.numeric(x) * 30.48 +
as.numeric(y) * 2.54, sub('"', '', df1$H)))
#[1] 187.96 177.80 165.10 154.94 165.10 162.56

3)分开

library(tidyverse)
df1 %>%
separate(H, into = c("H1", "H2"), convert = TRUE) %>%
transmute(H = H1 * 30.48 + H2 * 2.54)
# A tibble: 6 x 1
# H
# <dbl>
#1 188.
#2 178.
#3 165.
#4 155.
#5 165.
#6 163.

4)measurements

library(measurements)
library(tidyverse)
df1 %>%
separate(H, into = c("H1", "H2"), convert = TRUE) %>%
transmute(H = conv_unit(H1, "ft", "cm") + conv_unit(H2, "inch", "cm"))

关于r - 将以英寸为单位的高度字符向量转换为厘米?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55244198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com