0
点赞
收藏
分享

微信扫一扫

R中读写数据文件


一、首先确定当前工作目录,或者改变当前工作目录。


> getwd()
[1] "e:/RStudio"


>setwd("e:/RStudio")


二、读取纯文本文件的两个函数,一个是read.table(),另一个是scan()函数。


①read.table()


> r=read.table("test1.txt")
> r
  age sex weight height
1  25   F    175     56
2  21   M    172     55


> is.data.frame(r)
[1] TRUE


如果文件没有序号,用函数read.table("test1.txt",header=TRUE)会在数据前自动加上记录序号。


②scan()函数


> w=scan("test2.txt")
Read 30 items
> w
 [1] 172.4  75.0 169.3  54.8 169.3  64.0 171.4  64.8 166.5  47.4
[11] 171.4  62.2 168.2  66.9 165.1  52.0 168.8  62.2 167.8  65.0
[21] 165.8  62.2 167.8  65.0 164.4  58.7 169.9  57.5 164.9  63.5


 


> t=scan("test2.txt",list(height=0,weight=0))
Read 15 records
> t
$height
 [1] 172.4 169.3 169.3 171.4 166.5 171.4 168.2 165.1 168.8 167.8
[11] 165.8 167.8 164.4 169.9 164.9

$weight
 [1] 75.0 54.8 64.0 64.8 47.4 62.2 66.9 52.0 62.2 65.0 62.2 65.0
[13] 58.7 57.5 63.5


 


 


> x=matrix(scan("test2.txt"),nrow=3)
Read 30 items
> x
      [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
[1,] 172.4  54.8 171.4  47.4 168.2  52.0 167.8  62.2 164.4  57.5
[2,]  75.0 169.3  64.8 171.4  66.9 168.8  65.0 167.8  58.7 164.9
[3,] 169.3  64.0 166.5  62.2 165.1  62.2 165.8  65.0 169.9  63.5


 


三、读取excel文件,csv格式,这是数据最常见的格式,也是一些数据处理中应该比较熟悉的一种格式。


 


 >rc=read.csv("config1.csv")


得到的rc是一个数据框。


 


四、写数据文件


①write()函数


 


> df <- data.frame(


Name=c("Alice", "Becka", "James", "Jeffrey", "John"),


Sex=c("F", "F", "M", "M", "M"),Age=c(13, 13, 12, 13, 12),


Height=c(56.5, 65.3, 57.3, 62.5, 59.0),


Weight=c(84.0, 98.0, 83.0, 84.0, 99.5))


 


> write.table(df, file="foo.txt")


 


> write.csv(df, file="foo.csv")
两个函数的使用方法如下:


write.table(x, file = "", append = FALSE, quote = TRUE,


sep = " ", eol = "\n", na = "NA", dec = ".",


row.names = TRUE, col.names = TRUE,


qmethod = c("escape", "double"))

write.csv(..., col.names = NA, sep = ",",


qmethod = "double")
x 6 file 8 ' append=TRUE G 8 Æ m H 1
(FALSE, & B ) $ ) 8 sep 0 Q Æ - 8


其中x是对象,file是文件名,append=TRUE时,在源文件添加数据,否则是false的缺省值是写一个新文件。


 

举报

相关推荐

0 条评论