rbind/data.frame 转换类型层次结构 R [英] rbind/data.frame conversion type hierarchy R

查看:25
本文介绍了rbind/data.frame 转换类型层次结构 R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could anyone systematically explain to me the hierarchy of type conversion between character/numeric/factor while using rbind and data.frame?

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

In my understanding, rbind puts together in a matrix, which can only have one type. So if there's a type conflict, what's the type that will get converted to? Do other types of matrix-creation function (e.g. cbind, matrix) work the same way? Example:

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

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

On the other hand, a data frame can hold multiple types, so data.frame preserves the original type, EXCEPT that it always tries to convert character into factors. (Is this correct? This is very counter-intuitive to me.)

同样的逻辑,不管是factor(c(1,2))还是factor(c("a", "b"))?

With the same logic, is it correct that a factor type will always remain factor, no matter whether it is factor(c(1,2)) or 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"

推荐答案

看看 ?cbind(或 ?rbindValue 部分代码>):

Have a look at the Value section of ?cbind (or ?rbind):

从层次结构中任何输入的最高类型确定的矩阵结果类型原始<逻辑<整数<双<复杂<字符<列表"

"The type of a matrix result determined from the highest type of any of the inputs in the hierarchy raw < logical < integer < double < complex < character < list"

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

Some examples of coercion depending on the hierarchy:

# 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 中的数据框方法".

这篇关于rbind/data.frame 转换类型层次结构 R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆