代码之家  ›  专栏  ›  技术社区  ›  syre

将表转换为无因子的数据帧

  •  0
  • syre  · 技术社区  · 4 年前

    我希望在不将字符向量转换为因子的情况下将表转换为数据帧。然而 stringsAsFactors 在这种情况下,参数不能按预期工作。

    #create table
    (t <- table(c("a", "b"), c("c", "c")))   
    #    c
    #  a 1
    #  b 1
    
    #convert table into dataframe
    (df <- data.frame(t, stringsAsFactors=F))
    #  Var1 Var2 Freq
    #1    a    c    1
    #2    b    c    1
    
    #df column is factor
    class(df$Var1)
    [1] "factor"
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   U13-Forward    4 年前

    你需要 as.data.frame 相反 data.frame 不会修改原始因素:

    > df <- as.data.frame(t, stringsAsFactors=F)
    > class(df$Var1)
    [1] "character"
    >