代码之家  ›  专栏  ›  技术社区  ›  Omry Atia

将列类型重新转换为已读取的数据帧

  •  0
  • Omry Atia  · 技术社区  · 6 年前

    df1 (有许多列)我想与另一个数据帧连接 df2 应该具有相同的列类型。然而,由于某些原因,在书写和重读时,它们获得了不同的类型。

    当我想连接这些数据帧时,由于某些列不具有相同的类型(但应该具有相同的类型),它拒绝连接。

    df2型 对那些 ?

    例如:

    df1 <- data.frame(x = c(NA, NA, "3", "3"), y = c(NA, NA, "a", "b"))
    df1_class <- sapply(df1, class) #first, determine the different classes of df1
    df2 <- data.frame(x = c(NA, NA, 3, 3), y = c(NA, NA, "a", "b")) # df2 is 
    # equal to df1 but has a different class in column x
    
    # now cast column x of df2 as class "character" - but do this for all 
    # columns together because there are many columns....
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   krads    6 年前

    使用 purrr 以下包将更新df2以匹配df1类:

    df1_class <- sapply(df1, class)
    df2 <- 
      purrr::map2_df(
      df2,
      df1_class,
      ~ do.call(paste0('as.', .y), list(.x))
    )
    
        2
  •  1
  •   markus    6 年前

    ?mode 使用 "mode<-" 通过 Map

    df2[] <- Map(f = "mode<-", x = df2, value = df1_class)
    df2
    # A tibble: 4 x 3
    #  x     y         z
    #  <chr> <chr> <dbl>
    #1 NA    NA        2
    #2 NA    NA        2
    #3 3     a         2
    #4 3     b         2
    

    library(tibble)
    df1 <- data_frame(x = c(NA, NA, "3", "3"), y = c(NA, NA, "a", "b"), z = 1)
    df2 <- data_frame(x = c(NA, NA, 3, 3), y = c(NA, NA, "a", "b"), z = 2L)
    (df1_class <- sapply(df1, class))
    #          x           y           z 
    #"character" "character"   "numeric"