cbind()/data.frame()构建数据框字符串chr变因子Factor问题解决

来源:互联网 发布:java微信红包开发demo 编辑:程序博客网 时间:2024/06/06 03:02
cbind() 帮助文档中有这么一段话:
The cbind data frame method is just a wrapper for data.frame(..., check.names = FALSE). This means that it will split matrix columns in data frame arguments, and convert character columns to factors unless stringsAsFactors = FALSE is specified.
意思是cbind()构建数据框data frame的时候,如果参数有矩阵matrix,会拆分矩阵列,并将字符串列chr转换为因子Factor,但是可以用参数stringsAsFactors = FALSE指定关闭这个默认转换功能。

举例:

> a <- matrix(c('A','B','C','D'))> b <- data.frame(b=c('a','b','c','d'))> c <- data.frame(c=c('1','2','3','4'),stringsAsFactors = FALSE)> str(a) chr [1:4, 1] "A" "B" "C" "D"> str(b)'data.frame':4 obs. of  1 variable: $ b: Factor w/ 4 levels "a","b","c","d": 1 2 3 4> str(c)'data.frame':4 obs. of  1 variable: $ c: chr  "1" "2" "3" "4"#构建数据框时自动会将chr转换成Factor,观察b、c,使用stringsAsFactors参数明显可以阻止这一过程> cbind(a,b,c)  a b c1 A a 12 B b 23 C c 34 D d 4> class(cbind(a,b,c))[1] "data.frame"> str(cbind(a,b,c))'data.frame':4 obs. of  3 variables: $ a: Factor w/ 4 levels "A","B","C","D": 1 2 3 4 $ b: Factor w/ 4 levels "a","b","c","d": 1 2 3 4 $ c: chr  "1" "2" "3" "4"#合并矩阵matrix和数据框data.frame,会统一转换成data.frame,并将矩阵的字符串转为因子#cbind(a,b,c,stringsAsFactors = FALSE)> class(cbind(a,b,c,stringsAsFactors = FALSE))[1] "data.frame"> str(cbind(a,b,c,stringsAsFactors = FALSE))'data.frame':4 obs. of  3 variables: $ a: chr  "A" "B" "C" "D" $ b: Factor w/ 4 levels "a","b","c","d": 1 2 3 4 $ c: chr  "1" "2" "3" "4"#stringsAsFactors参数可以阻止这一转化#data.frame(a,b,c)> class(data.frame(a,b,c))[1] "data.frame"> str(data.frame(a,b,c))'data.frame':4 obs. of  3 variables: $ a: Factor w/ 4 levels "A","B","C","D": 1 2 3 4 $ b: Factor w/ 4 levels "a","b","c","d": 1 2 3 4 $ c: chr  "1" "2" "3" "4"#在这里data.frame()效果和cbind()一致#data.frame(a,b,c,stringsAsFactors = FALSE)> class(data.frame(a,b,c,stringsAsFactors = FALSE))[1] "data.frame"> str(data.frame(a,b,c,stringsAsFactors = FALSE))'data.frame':4 obs. of  3 variables: $ a: chr  "A" "B" "C" "D" $ b: Factor w/ 4 levels "a","b","c","d": 1 2 3 4 $ c: chr  "1" "2" "3" "4"#stringsAsFactors参数在这里同样有效#附:两个矩阵的合并依旧是矩阵,但是用data.frame()会变成数据框以及Factor> a <- matrix(c('1','2','3','4'))> b <- matrix(c('a','b','c','d'))> class(data.frame(a,b))[1] "data.frame"> str(data.frame(a,b))'data.frame':4 obs. of  2 variables: $ a: Factor w/ 4 levels "1","2","3","4": 1 2 3 4 $ b: Factor w/ 4 levels "a","b","c","d": 1 2 3 4> class(cbind(a,b))[1] "matrix"> str(cbind(a,b)) chr [1:4, 1:2] "1" "2" "3" "4" "a" "b" "c" "d"

原创粉丝点击