本文介绍了rbind / data.frame转换类型层次结构R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 在我的理解中, 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 #integer b< - 0:1 #double c< - c(0,1.0) # $ bd< - c(0,1) m1< - cbind(a,b) m1 str(m1) #逻辑转换为整数 m2 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:# logicala <- c(FALSE, TRUE)# integerb <- 0:1# doublec <- c(0, 1.0)# characterd <- c("0", "1")m1 <- cbind(a, b)m1str(m1)# logical converted to integerm2 <- cbind(b, c)m2str(m2)# integer converted to doublem3 <- cbind(c, d)m3str(m3)# double converted to characterSee also "Data frame methods" in ?cbind. 这篇关于rbind / data.frame转换类型层次结构R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-24 11:52