参考书《R语言实战(第2版)》
建议大家购买正版图书学习
昨天的内容有点遗漏,我补充在这里
#导入数据时,如果用到JAVA相关的包,记得先加载rjava包> library(xlsx)> library(rJava)> workbook "D:/XXX/studentgrades.xlsx"> mydataframe > mydataframe
好啦,开始今天的内容
数据集标注:为变量名添加描述性标签+为类别型变量中的编码添加值标签
#用factor()函数创建值标签> gender c(> ID c(> dataframe1 ID)> dataframe1 gender ID1 1 12 1 23 2 34 2 45 1 56 2 6> dataframe1$gender c(Error in factor(dataframe1$gender, levels = c(1, 2), lables = c("male", : unused argument (lables = c("male", "female"))> dataframe1$gender c(> dataframe1$gender[1] male male female female male femaleLevels: male female
常用函数汇总-处理数据对象
length(object)#显示对象中元素、成分的数量dim(object)#显示某个对象的维度str(object)#显示某个对象的结构class(object)#显示某个对象的类或类型mode(object)#显示某个对象的模式names(object)#显示某对象中各成分的名称c(object1,object2,...)#将对象合并入一个向量cbind(object1,object2,...)#按列合并对象rbind(object1,object2,...)#按行合并对象object#输出某个对象head(object)#列出某个对象开始的几行tail(object)#列出某个对象最后的几行ls()#显示当前的对象列表rm(object1,object2,...)#删除一个或更多个对象rm(list = ls())#删除当前工作环境中几乎全部对象newobject object)fix(object)#直接编辑对象fix(mydataframe)#调用文本编辑器来编辑数据框,直接在文本编辑器里加减变量、修改变量数据类型很方便
R数据的导出
符号分隔文本文件
#write.table()> ?write.table#查看函数用法write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ", eol = "\n", na = "NA", dec = ".", row.names = TRUE, col.names = TRUE, qmethod = c("escape", "double"), fileEncoding = "")write.csv(...)write.csv2(...)
#举例> write.table(dataframe1,"D:/XXX/dataframe1.txt",sep=",")
Excel电子表格
#xlsx包中的write.xlsx()函数> library(xlsx)> ?write.xlsx2write.xlsx( x, file, sheetName = "Sheet1", col.names = TRUE, row.names = TRUE, append = FALSE, showNA = TRUE, password = NULL)
#举例> library(xlsx)> write.xlsx(dataframe1,"D:/XXX/dataframe1.xlsx")
SPSS等外部统计软件文件
#foreign包中的write.foreign()函数,会创建两个文件,文本文件和编码文件> library(foreign)> ? write.foreignwrite.foreign(df, datafile, codefile, package = c("SPSS", "Stata", "SAS"), ...)
#举例> library(foreign)> write.foreign(dataframe1, "D:/XXX/dataframe1.txt", "D:/XXX/dataframecode1.sps",package = "SPSS")
今天的内容比较简单。