【问题标题】:rbind/data.frame conversion type hierarchy Rrbind/data.frame 转换类型层次结构 R
【发布时间】:2014-03-12 20:51:58
【问题描述】:

在使用 rbind 和 data.frame 时,谁能系统地向我解释字符/数字/因子之间类型转换的层次结构?

在我的理解中,rbind 放在一个矩阵中,矩阵只能有一种类型。因此,如果存在类型冲突,将转换为什么类型?其他类型的矩阵创建函数(例如cbindmatrix)是否以同样的方式工作?示例:

> sapply(rbind("a", "b"), class)
      a           b 
"character" "character" 
> sapply(rbind(1, "b"), class)
          1           b 
"character" "character" 

另一方面,一个数据框可以包含多种类型,因此data.frame 保留原始类型,除了它总是尝试将字符转换为因子。 (这是正确的吗?这对我来说非常违反直觉。)

同样的逻辑,不管是factor(c(1,2))还是factor(c("a", "b")),一个因子类型永远保持因子是正确的吗?

> sapply(data.frame("a", "b"), class)
    X.a.     X.b. 
"factor" "factor" 
> sapply(data.frame(1, "b"), class)
       X1      X.b. 
"numeric"  "factor"
> sapply(data.frame(1, factor("a")), class)
     X1 factor..a.. 
  "numeric"    "factor"

【问题讨论】:

  • data.frame 或您的全局选项中查看参数stringsAsFactors
  • 我知道有这样的事情。我要求系统地解释哪种类型在转换中具有优先权。

标签: r matrix type-conversion dataframe


【解决方案1】:

查看?cbind(或?rbind)的Value部分:

"从层次结构中任何输入的最高类型确定的矩阵结果类型 raw

根据层次结构的一些强制示例:

# logical
a <- c(FALSE, TRUE)

# integer
b <- 0:1

# double
c <- c(0, 1.0)

# character
d <- c("0", "1")


m1 <- cbind(a, b)
m1
str(m1)
# logical converted to integer

m2 <- cbind(b, c)
m2
str(m2)
# integer converted to double

m3 <- cbind(c, d)
m3
str(m3)
# double converted to character

另请参阅?cbind 中的“数据框方法”。

【讨论】:

  • 该列表中的因素在哪里?
  • 整数。检查f1 &lt;- factor(0:1)f2 &lt;- factor(c("0", "1")); typeof(f1); typeof(f2)。请参阅?factor:“类“因子”的对象,它具有一组长度为 x 的整数代码,具有模式字符的“级别”属性”。
猜你喜欢
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 2016-09-14
  • 2013-03-20
  • 1970-01-01
  • 2013-12-25
相关资源
最近更新 更多