【问题标题】:Different result in the case of `factor` or `as.factor`?在 `factor` 或 `as.factor` 的情况下结果不同?
【发布时间】:2019-04-03 02:25:46
【问题描述】:

我的系统是 R 3.5.3 和 Rstudio 1.1.463

设置数据框如下:

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'] &lt;- lapply(df['cola'], function(x) factor(x,levels=cats,exclude = NULL,ordered = FALSE,nmax=6)),得到预期的结果。

如果factor改为as.factor基于on this post,运行df['cola'] &lt;- 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)

有什么问题?

【问题讨论】:

  • 这些参数在factor 而不是as.factor
  • as.factor is a wrapper for factor 在那个帖子中误导了我
  • 这意味着as.factor“自动”执行您在factor中手动执行的操作。

标签: r


【解决方案1】:

问题如错误消息中所述。您正在传递 as.factor 不存在的参数。如果您阅读?as.factor,您会看到as.factor 的参数只有xlevelsexcludeorderednmaxfactor 的参数,而不是 as.factor。因此,它会给您错误,您正在传递您没有使用的参数。

如果您删除这些参数并运行该函数,则它可以正常工作而不会出现任何错误消息。

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)

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2012-01-28
    • 2018-01-24
    • 2018-06-07
    相关资源
    最近更新 更多