【问题标题】:converting units (ft to cm) entered as factors to integers in R将作为因子输入的单位(英尺到厘米)转换为 R 中的整数
【发布时间】:2018-05-01 16:41:20
【问题描述】:

我正在尝试在 R 中编写一个函数,它将以不同单位输入的高度转换为厘米。

在数据框中,以厘米(例如 175)、米(例如 1.83)或英尺和英寸(例如 5ft4 甚至 5ft9.5)为单位输入高度。 我需要做的是将包含字符(“ft”或“.”)的因子转换为整数,但我不知道如何实际处理。

任何帮助都会非常受欢迎:)

【问题讨论】:

  • 到目前为止你做了什么,问题出在哪里?
  • gsub('ft|[.]','',c('5ft4','5ft9.5'))
  • 所以我处于非常基本的 R 水平,甚至似乎无法将数据帧的因子转换为整数。我试图创建一个 for-if 循环并使用 grepl 函数返回包含 ft 的元素,但由于它们甚至不是整数,我不知道如何将它们转换为可以使用转换因子的状态。跨度>
  • 获取一本介绍 R 入门的书并开始这样做。然后你就会学会。可能你现在面临的挑战太大了。路也不是很清楚,好像

标签: r units-of-measurement


【解决方案1】:

这可能有效。

  library(dplyr)
  library(stringr)

  df <- tibble(measurementType = c("feet", "cm", "m"), height = c("5ft8.5", 175, 1.83))

  df %>% mutate(height = ifelse(measurementType == "feet",
                                 as.numeric(unlist(str_split(height, "ft"))[1]) * 12 + as.numeric(unlist(str_split(height, "ft"))[2]), 
                                as.numeric(height))) %>% 
       mutate(heightInCm = case_when(measurementType == "feet" ~ height * 2.54,
                                     measurementType == "m" ~ height * 100,
                                     TRUE ~ height))

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多