【问题标题】:Map as.numeric to only specific columns of a dataframe仅将 as.numeric 映射到数据框的特定列
【发布时间】:2020-02-15 03:38:11
【问题描述】:

我有一些格式如下的数据,其中所有列的类型均为chr

#> # A tibble: 3 x 4
#>   id    age   name  income
#>   <chr> <chr> <chr> <chr> 
#> 1 1     18    jim   100   
#> 2 2     21    bob   200   
#> 3 3     16    alice 300

我只想在某些列上使用as.numeric()。最好,我想定义一个列名向量,然后使用 purrr:mapas.numeric() 映射到这些列:

numeric_variables <- c("id", "age", "income")

我怎样才能map那个?

我想要的输出如下所示:


df
#> # A tibble: 3 x 4
#>      id   age name  income
#>   <dbl> <dbl> <chr>  <dbl>
#> 1     1    18 jim      100
#> 2     2    21 bob      200
#> 3     3    16 alice    300

下面的数据输入代码。

library(purrr)
df <- data.frame(stringsAsFactors=FALSE,
          id = c(1, 2, 3),
         age = c(18, 21, 16),
        name = c("jim", "bob", "alice"),
      income = c(100, 200, 300)
)
df <- map_df(df, as.character)
df

reprex package (v0.3.0) 于 2020-02-15 创建

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    我们可以使用mutate_at

    library(dplyr)
    df %>%
      mutate_at(vars(numeric_variables), as.numeric) %>%
      as_tibble
    # A tibble: 3 x 4
    #     id   age name  income
    #  <dbl> <dbl> <chr>  <dbl>
    #1     1    18 jim      100
    #2     2    21 bob      200
    #3     3    16 alice    300
    

    或者更容易

    df %>%
        type.convert(as.is = TRUE)
    

    map

    library(purrr)
    df %>%
       map_if(names(.) %in% numeric_variables, as.numeric) %>%
       bind_cols
    # A tibble: 3 x 4
    #     id   age name  income
    #  <dbl> <dbl> <chr>  <dbl>
    #1     1    18 jim      100
    #2     2    21 bob      200
    #3     3    16 alice    300
    

    或者如果我们使用复合赋值运算符(%&lt;&gt;%),这可以就地赋值

    library(magrittr)
    df %<>%
       map_if(names(.) %in% numeric_variables, as.numeric) %<>%
       bind_cols
    str(df)
    #tibble [3 × 4] (S3: tbl_df/tbl/data.frame)
    # $ id    : num [1:3] 1 2 3
    # $ age   : num [1:3] 18 21 16
    # $ name  : chr [1:3] "jim" "bob" "alice"
    #  $ income: num [1:3] 100 200 300
    

    【讨论】:

      【解决方案2】:

      您可以使用map_at

      df[] <- purrr::map_at(df, numeric_variables, as.numeric)
      df
      # A tibble: 3 x 4
      #     id   age name  income
      #  <dbl> <dbl> <chr>  <dbl>
      #1     1    18 jim      100
      #2     2    21 bob      200
      #3     3    16 alice    300
      

      【讨论】:

      • 不知道您能否告诉我为什么我们必须在df[] 中使用方括号?我以前没见过。有没有这个词的名字,我可以用谷歌搜索更多信息?
      • @JeremyK。如果您检查purrr::map_at(df, numeric_variables, as.numeric) 的输出,它会返回一个列表,通过使用[],我们会维护数据框df 的原始维度。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 2019-03-21
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多