【问题标题】:Converting character to integer when it is possible尽可能将字符转换为整数
【发布时间】:2022-01-18 19:11:03
【问题描述】:

我有以下数据框:

y  <- c("11 - 14", "13 - 17", "13 - 19")
x1 <- c(10, 11, 8)
x2 <- c(31, 30, 30)

df <- data.frame(y, x1, x2)

如何将字符转换为唯一整数,例如均值?

例如,"11 - 14" 变为 12.5

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    拆分" - ",然后将每个转换为数字并取平均值。

    y_split <- strsplit(df$y, " - ")
    df$y <- sapply(y_split, function(x) mean(as.numeric(x)))
    df
    #>      y x1 x2
    #> 1 12.5 10 31
    #> 2 15.0 11 30
    #> 3 16.0  8 30
    

    【讨论】:

      【解决方案2】:

      与其他答案相同的方法,但使用 tidyverse 包:

      library(purrr)
      library(stringr)
      library(dplyr)
      df %>%
        mutate(
          y_nums = str_extract_all(y, pattern = "[[:digit:]]+"),
          result = map(y_nums, .f = ~mean(as.numeric(.)))
        )
      #         y x1 x2 y_nums result
      # 1 11 - 14 10 31 11, 14   12.5
      # 2 13 - 17 11 30 13, 17     15
      # 3 13 - 19  8 30 13, 19     16
      

      【讨论】:

        【解决方案3】:

        我们可以使用 rowMeansread.table 来执行此操作 - 使用 read.table 读取列 'y' 以创建两列,并使用 rowMeansbase R 中获取行均值

        df$result <- rowMeans(read.table(text=df$y, sep="-", strip.white = TRUE))
        

        -输出

        > df
                y x1 x2 result
        1 11 - 14 10 31   12.5
        2 13 - 17 11 30   15.0
        3 13 - 19  8 30   16.0
        

        【讨论】:

          【解决方案4】:

          基于 R 的另一个选项:

          df$y <- do.call(rbind, strsplit(df$y, "-")) |>
            type.convert(as.is = TRUE) |>
            rowMeans()
          

          给出:

          > df
               y x1 x2
          1 12.5 10 31
          2 15.0 11 30
          3 16.0  8 30
          

          甚至是另一种选择(虽然不强烈推荐):

          df$y <- sapply(sub("-", "+", df$y), \(x) eval(parse(text = x))) / 2
          

          【讨论】:

            猜你喜欢
            • 2021-01-09
            • 2014-12-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多