【问题标题】:R convert data to factor will corrupt all other data.frame columnsR将数据转换为因子将损坏所有其他data.frame列
【发布时间】:2015-07-15 04:52:45
【问题描述】:

我有一个 data.frame,所有列都是数字。我想将一个整数列转换为因子,但这样做会将所有其他列转换为类字符。无论如何只将一列转换为因子?

例子来自Converting variables to factors in R

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)
myData$A <-as.factor(myData$A)

结果

apply(myData,2,class)
#           A           B       Pulse 
# "character" "character" "character" 

sessionInfo()

R version 3.1.2 (2014-10-31) 
Platform: x86_64-apple-darwin13.4.0 (64-bit) 

locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8  
attached base packages: 
[1] splines stats graphics grDevices utils datasets methods base ... 

str(myData$A)
# Factor w/ 2 levels "1","2": 1 2 1 2 1 2

【问题讨论】:

  • 为我工作。你的sessionInfo() 是什么?
  • 这似乎不太可能。您提供的代码是否真的为您重现了问题?
  • 我唯一知道发生这种情况的是myData 是矩阵、数组或向量,而不是数据帧。你确定class(myData) 是一个数据框(对于导致你出现问题的任何数据)?
  • class(myData) data.frameapply(myData,2,class) 产生 A B 脉冲“字符”“字符”“字符”
  • @Pascal sessionInfo()R version 3.1.2 (2014-10-31) Platform: x86_64-apple-darwin13.4.0 (64-bit) locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 attached base packages: [1] splines stats graphics grDevices utils datasets methods base ...

标签: r


【解决方案1】:

您的代码在我测试时确实有效。

这是我来自str(myData)的输出:

    'data.frame':   6 obs. of  3 variables:
 $ A    : Factor w/ 2 levels "1","2": 1 2 1 2 1 2
 $ B    : int  1 2 3 1 2 3
 $ Pulse: int  20 21 22 23 24 25

您的问题是因为,正如?apply 所说:

“应用”尝试强制 如果数组是二维的(例如,数据 框架)

这是在对每一列执行函数之前完成的。当你运行as.matrix(myData) 时,你最终会被强制归为一类,在这种情况下是字符数据:

is.character(as.matrix(myData))
#[1] TRUE

【讨论】:

  • @thelatemail 您在此处所做的编辑非常慷慨。
  • @davidarenburg - 我现在正处于退休比尔盖茨阶段。分享我所说的观点。
猜你喜欢
  • 1970-01-01
  • 2011-02-20
  • 2018-05-17
  • 1970-01-01
  • 2014-01-05
  • 2012-03-04
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多