版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/X_dmword/article/details/81876653
R语言的输出函数有cat、sink、writeLines、write.table
1)cat
cat函数即能输出到屏幕,也能输出到文件
cat(... , file = "", sep = " ", fill = FALSE, labels = NULL,append = FALSE)
eg:
>cat("要添加的内容") ##结果:要添加的内容
>cat("a",file="d:/面试.txt",append=TRUE) ##再次打开面试.txt最后多了a
2)sink
sink函数将输出结果定向到文件
sink(file = NULL, append = FALSE, type = c("output", "message"),split = FALSE)
eg:
> sink("d:/面试.txt") ##以下的内容定向输入到面试
> cat("shemegui") ##清除面试原内容,添加
> cat("jssjjs") ##继续添加
> sink("d:/面试.txt") ##重定向
> cat("qqqqqq") ##再次清除添加
3)writeLines
writeLines函数将字符串向量输出到文件中(会覆盖原始内容)
writeLines(text, con = stdout(), sep = "\n", useBytes = FALSE)
eg:
> a<-c("haha","hehe")
> writeLines(a,con="d:/面试.txt",sep="\t") ##结果:haha hehe
> a=c("hahaha","hehehe") ##可以=号
> writeLines(a,con="d:/面试.txt",sep="\n") ##换行
4)write.table
write.table函数将dataframe的内容输出到文件
参数说明
x | 写入的对象的名称 |
file | 文件名(缺省时对象直接被“写”在屏幕上) |
append | 是否为增量写入 |
quote | 一个逻辑型或者数值型向量:如果为TRUE,则字符型变量和因子写在双引 号""中;若quote是数值型向量则代表将欲写在""中的那些列的列标。(两种 情况下变量名都会被写在""中;若quote = FALSE则变量名不包含在双引号中) |
sep | 文件中的字段分隔符 |
eol | 指定行尾符,默认为'\n' |
na | 表示缺失数据的字符 |
dec | 用来表示小数点的字符 |
row.names | 一个逻辑值,决定行名是否写入文件;或指定要作为行名写入文件的字符型 向量 |
col.names | 一个逻辑值(决定列名是否写入文件);或指定一个要作为列名写入文件中 的字符型向量 |
qmethod | 若quote=TRUE,则此参数用来指定字符型变量中的双引号"如何处理: 若参数值为"escape" (或者"e",缺省)每个"都用\"替换;若值为"d"则每 个"用""替换 |
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 = "")
eg:
> m<-matrix(1:12,nrow=3)
> dd=as.data.frame(m)
> write.table(dd,file="d:/面试.txt",append=TRUE,row.names=FALSE)
##结果(加了列名)
hahaha
hehehe
"V1" "V2" "V3" "V4"
1 4 7 10
2 5 8 11
3 6 9 12
> write.table(dd,file="d:/面试.txt",append=TRUE,col.names=FALSE)
##再加一句,结果
hahaha
hehehe
"V1" "V2" "V3" "V4"
1 4 7 10
2 5 8 11
3 6 9 12
"1" 1 4 7 10
"2" 2 5 8 11
"3" 3 6 9 12
> write.table(dd,file="d:/面试.txt",append=F)
##继续测试
"V1" "V2" "V3" "V4"
"1" 1 4 7 10
"2" 2 5 8 11
"3" 3 6 9 12
输出为表格:
> write.csv(dd,file="d:/tab.csv")
> write.table(dd,file="d:/sb.csv")
>write.csv(dd,file="d:/sb.xls")
>write.table(dd,file="d:/sb.xlsx") ##结果一致
以下纯粹闹着玩的