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

“factor”或“as.factor”的结果不同?

r
  •  1
  • kittygirl  · 技术社区  · 5 年前

    设置数据帧如下:

    df <- data.frame(
        cola = c('a','b','c','d','e','e','1',NA,'c','d'),
        colb = c("A",NA,"C","D",'a','b','c','d','c','d'),stringsAsFactors = FALSE)
    cats<-c('a','b','c','d','e','f','1')
    

    然后,快跑 df['cola'] <- lapply(df['cola'], function(x) factor(x,levels=cats,exclude = NULL,ordered = FALSE,nmax=6)) ,得到了预期的结果。

    如果 factor as.factor on this post ,运行 df['cola'] <- lapply(df['cola'], function(x) as.factor(x,levels=cats,exclude = NULL,ordered = FALSE,nmax=6))

    Error in as.factor(x, levels = cats, exclude = NULL, ordered = FALSE,  : 
      unused arguments (levels = cats, exclude = NULL, ordered = FALSE, nmax = 6)
    

    有什么问题吗?

    1 回复  |  直到 5 年前
        1
  •  4
  •   Ronak Shah    5 年前

    问题如错误消息中所述。你所传递的论据对我来说是不存在的 as.factor . 如果你阅读 ?as.factor 您可以看到 只是 x . levels , exclude , ordered , nmax 是支持 factor 而不是 as.系数

    如果删除这些参数并运行该函数,则该函数不会出现任何错误消息。

    lapply(df['cola'], function(x) as.factor(x))
    #$cola
    # [1] a    b    c    d    e    e    1    <NA> c    d   
    #Levels: 1 a b c d e
    

    或者只是

    lapply(df['cola'], as.factor)
    

    如果你只有一个专栏,就不需要 lapply

    as.factor(df$cola)