character or Factor.rar
(933 Bytes)
本附件包括:- character or Factor.R
于是,决定写这篇帖子和各位新手们分享。共同进步,少走弯路。
当然,我自己也收集了一些其他的小问题的处理方法,以后有机会再写。
- ###### R语言新手解惑之:为什么我的字符串造反了? #####
- #### 先生成一个字符串向量 ####
- rep<-paste("rep",1:100,sep="")#生成字符串rep1,...,rep100
- rep<-sample(rep,100,replace = FALSE)#随机调整顺序
- rep[1:6]
- other<-round(runif(100,6,10))#生成均匀分布随机数并四舍五入取整
- other[1:6]
- is(rep)#查看数据类型,是"character" 、"vector"
- is(other)##查看数据类型,是"numeric" 、"vector"
- #### 接下来将上述两列数据合并成数据框,并查看stringAsFactor参数带来的影响 ####
- #### 1:data.frame(rep,other,stringAsFactor=TRUE) ####
- #stringASFactor=TRUE 为默认设置 #
- data<-data.frame(rep,other,stringsAsFactors = TRUE)
- head(data)
- class(data$rep)#显然此时data$rep已经转换成因子了,而不是字符串了
- data1<-data.frame(rep,other)#等价于data.frame(rep,other,stringsAsFactors = TRUE)
- head(data1)
- class(data1$rep)#显然此时data1$rep已经转换成因子了,而不是字符串了
- #### 2:data.frame(rep,other,stringAsFactor=FALSE) ####
- dataF<-data.frame(rep,other,stringsAsFactors = FALSE)
- head(dataF)
- class(dataF$rep)#此时dataF$rep是字符串,正是我们想要保留的数据类型
- #### 3:R中内置的一些数据读取的函数都设置有stringASFactor=TRUE 这个默认参数 ####
- ?read.table
- ?read.csv
- ?read.delim
- ?data.frame
- #### 小结:因此我们在利用上述函数(上面展示的仅仅是部分)输入数据时,
- ####要留意自己是否要保留字符串向量的格式,还是要转换成因子去处理,
- #### 这些函数默认将字符串处理成因子
- > rep<-paste("rep",1:100,sep="")#生成字符串rep1,...,rep100
- > rep<-sample(rep,100,replace = FALSE)#随机调整顺序
- > rep[1:6]
- [1] "rep22" "rep30" "rep17" "rep96" "rep55" "rep84"
- > other<-round(runif(100,6,10))#生成均匀分布随机数并四舍五入取整
- > other[1:6]
- [1] 7 7 10 10 6 7
- > is(rep)#查看数据类型,是"character" 、"vector"
- [1] "character" "vector" "data.frameRowLabels"
- [4] "SuperClassMethod"
- > is(other)##查看数据类型,是"numeric" 、"vector"
- [1] "numeric" "vector"
- > data<-data.frame(rep,other,stringsAsFactors = TRUE)
- > head(data)
- rep other
- 1 rep22 7
- 2 rep30 7
- 3 rep17 10
- 4 rep96 10
- 5 rep55 6
- 6 rep84 7
- > class(data$rep)#显然此时data$rep已经转换成因子了,而不是字符串了
- [1] "factor"
- > data1<-data.frame(rep,other)#等价于data.frame(rep,other,stringsAsFactors = TRUE)
- > class(data1$rep)#显然此时data1$rep已经转换成因子了,而不是字符串了
- [1] "factor"
- > dataF<-data.frame(rep,other,stringsAsFactors = FALSE)
- > head(dataF)
- rep other
- 1 rep22 7
- 2 rep30 7
- 3 rep17 10
- 4 rep96 10
- 5 rep55 6
- 6 rep84 7
- > class(dataF$rep)#此时dataF$rep是字符串,正是我们想要保留的数据类型
- [1] "character"
- > ?read.table
- > ?read.csv
- > ?read.delim
- > ?data.frame


雷达卡




京公网安备 11010802022788号







