rbind / data.frame转换类型层次结构R [英] rbind/data.frame conversion type hierarchy R
问题描述
在我的理解中,<$ c()可以在系统地向我解释使用rbind和data.frame之间的字符/数字/因子之间的类型转换的层次结构?
< $ c> rbind 将其放在一个只能有一个类型的矩阵中。所以如果有类型冲突,那么转换为什么类型?做其他类型的矩阵创建功能(例如
cbind
, matrix
)的工作方式相同吗?示例: > sapply(rbind(a,b),class)
a b
charactercharacter
> sapply(rbind(1,b),class)
1 b
charactercharacter
$ b $另一方面,数据帧可以保存多种类型,因此 data.frame
保留原始类型,EXCEPT它始终尝试转换人物因素。 (这是否正确?这对我来说非常直观)。
与同样的逻辑,一个因素类型将始终保持因素是正确的,无论是否(c(1,2))或 factor(c(a,b))
?
> sapply(data.frame(a,b),class)
X.a. X.b.
factorfactor
> sapply(data.frame(1,b),class)
X1 X.b.
numericfactor
> sapply(data.frame(1,factor(a)),class)
X1 factor..a ..
numericfactor
看看的价值部分? cbind
(或?rbind
):
确定矩阵结果的类型从层次结构中的任何输入的最高类型原始<逻辑< integer< double< complex< character< list< list"
强制取决于层次结构:
#logical
a < - c(FALSE,TRUE)
#integer
b< - 0:1
#double
c< - c(0,1.0)
# $ bd< - c(0,1)
m1< - cbind(a,b)
m1
str(m1)
#逻辑转换为整数
m2 < - cbind(b,c)
m2
str(m2)
#整数转换为双
m3< - cbind(c,d)
m3
str(m3)
#double convert to characte r
另请参阅数据框方法 >?cbind
。
Could anyone systematically explain to me the hierarchy of type conversion between character/numeric/factor while using rbind and data.frame?
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"
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.)
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"
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
See also "Data frame methods" in ?cbind
.
这篇关于rbind / data.frame转换类型层次结构R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!