有许多方法可以将R对象导出为其他格式。对于SPSS、SAS和Stata,用foreign
packages,对于Excel,用xlsReadWrite
包。
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 = "")
选项 | 描述 |
---|---|
x |
要写入文件的变量,数据框或者矩阵 |
file |
文件名(缺省时对象直接被“写”在屏幕上) |
append | 逻辑值。只有当file为字符串时才相关。如果为TRUE则在写入数据时继续加在原文件中,采取往后添加的方式;如果为False,则覆盖之前的东西 |
quote | 逻辑型或者数值向量:如果为TRUE,则字符型变量和因子写在双引号("")中,若quote是数值型向量则代表将欲写在("")中的那些列的列标;如为FALSE,则nothing is quoted |
sep |
文件中的字段分隔符 |
eol |
使用在每行最后的字符("\n"表示回车)eol = "\r"为Excel:mac 2004标准 |
na | 表示确实数据的字符 |
dec | 用来表示小数点的字符 |
row.names | 逻辑值(决定行名是否写入文件)或字符向量(行名) |
col.names | 逻辑值(决定列名是否写入文件)或字符向量(作为列名写入文件中) |
qmethod | a character string specifying how to deal with embedded double quote characters when quoting strings. Must be one of "escape" (default for write.table), in which case the quote character is escaped in C style by a backslash, or "double" (default for write.csv and write.csv2), in which case it is doubled. You can specify just the initial letter. |
1 导出为文本文档
write.table(mydata,"shuchu3.txt", sep = "\t", row.names = c("w","b","e","w","t")) #不加sep="\t",数据会黏在一起;行名一定要对应行数,多或少会报错
2 导出为excel
library(xlsx)
write.xlsx(mydata, "shuchu.xlsx")
问题:why?
write.xlsx(mydata,"shuchu3.xlsx",row.names = c("o","e","w","e","q"))
报错: Error in if (row.names) jOffset <- 1 : argument is not interpretable as logical In addition: Warning message: In if (row.names) jOffset <- 1 : the condition has length > 1 and only the first element will be used
3 导出到SPSS
# write out text datafile and
# an SPSS program to read it
library(foreign)
write.foreign(mydata, "c:/mydata.txt", "c:/mydata.sps", package="SPSS")
4 导出为SAS
# write out text datafile and
# an SAS program to read it
library(foreign)
write.foreign(mydata, "c:/mydata.txt", "c:/mydata.sas", package="SAS")
5 导出为Stata
library(foreign)
write.dta(mydata, "c:/mydata.dta")
问题:
- 导出为csv时,加了append = TRUE,虽然报错
Warning message: In write.table(w, "expfuben.csv", sep = ",", row.names = T, append = TRUE) : 给文件加列名
,但依然将更改过的表格写在了原文件内,原文件的内容还保留。 -
正常表达量矩阵文件exp.csv,
image.png
w<- read.table("exp.csv", header = T, sep = ",")
write.table(w,"expfuben2.csv",sep = ",")
为什么第一列变成了序号,而原来的列名从第一列开始,导致错位,如下:
image.png
网友评论