【问题标题】:Why does R convert character to factor为什么R将字符转换为因子
【发布时间】:2015-03-01 05:07:23
【问题描述】:

R 新手,无法弄清楚这一点。我有一个字符向量,将其放入 data.frame 中,它们变为“因子”:

> name <- c("Ann","Bob", "Carl", "Dan","Ed")  
> class(name)
    [1] "character"  # Expected this.
> wt <- c(123,234,222,199,201)
> class(wt)
    [1] "numeric"    # Expected this.   
> a <- data.frame(name, wt)
> class(a$wt)
    [1] "numeric"    # Expected this.
> class(a$name)
    [1] "factor"     # ???

我不确定为什么会这样。

【问题讨论】:

  • 如果你看data.frame函数,stringsAsFactors = default.stringsAsFactors())就是stringsAsFactors=TRUE
  • 只有当getOption("stringsAsFactors") 为 TRUE 或 NULL 时,default.stringsAsFactors() 才为 TRUE。打开 R 时它默认为 TRUE。它都记录在 help(data.frame)

标签: r


【解决方案1】:

如 cmets 中所述,在创建 data.frame 时使用 stringsAsFactors = FALSE

str(data.frame(name, wt, stringsAsFactors = FALSE))
# 'data.frame':  5 obs. of  2 variables:
#  $ name: chr  "Ann" "Bob" "Carl" "Dan" ...
#  $ wt  : num  123 234 222 199 201

默认行为是stringsAsFactors = TRUE。此默认行为可以在启动时更改,但您可能不希望这样做以与其他人的脚本兼容。

其他一些基于data.frames 的包有不同的默认行为。例如,考虑“data.table”包中的data.table 或“dplyr”包中的data_frame

library(data.table)
str(data.table(name, wt))
# Classes ‘data.table’ and 'data.frame':  5 obs. of  2 variables:
#  $ name: chr  "Ann" "Bob" "Carl" "Dan" ...
#  $ wt  : num  123 234 222 199 201
# - attr(*, ".internal.selfref")=<externalptr> 

library(dplyr)
str(data_frame(name, wt))
# Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 5 obs. of  2 variables:
#  $ name: chr  "Ann" "Bob" "Carl" "Dan" ...
#  $ wt  : num  123 234 222 199 201

【讨论】:

  • 谢谢你,我什至没有想到查看设置/选项。
猜你喜欢
  • 2020-10-05
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
相关资源
最近更新 更多