获取数据 的途径
- 利用键盘输入数据
- 读取存储在外部文件上的数据
- 访问数据库系统来获取数据
1. 利用键盘输入数据
Ⅰ.集成数据框data.frame
> patientID <- c(1, 2, 3, 4)
> admdate <- c("10/15/2009","11/01/2009","10/21/2009","10/28/2009")
> age <- c(25, 34, 28, 52)
> diabetes <- c("Type1", "Type2", "Type1", "Type1")
> status <- c("Poor", "Improved", "Excellent", "Poor")
> data <- data.frame(patientID, age, diabetes, status)
> data
patientID age diabetes status
1 1 25 Type1 Poor
2 2 34 Type2 Improved
3 3 28 Type1 Excellent
4 4 52 Type1 Poor
> class(admdate)
[1] "character"
Ⅱ.编辑数据库edit( )
> data2 <- data.frame(patientID=character(0), age=numeric(0),
+ diabetes=character(), status=character())
> data2 <- edit(data2)
> fix(data2)
2. 读取存储在外部文件上的数据
- .csv 逗号分隔文件(Comma-Separated Values)
- .txt 空格分隔文件
> setwd(" ") 修改工作路径
> getwd(" ") 查看工作路径
> read.table("Rdata/input.txt") 工作路径下的文件夹里的文件(/或者\\),记得加文件格式(.txt/.csv)***********
> head(x)
> tail(x,10) 查看前/后几行数据,默认6行,可自定义
***************************其中header=T表示将文件中第一行设为列名字。 row.names= 1表示第一列设为行名
> read.table(x,header= T ,skip=5) 跳过前5行
> read.table(x,header=T,skip=50,nrows=200) 读取第51-250行——第51行作为表头
-
read.fwf( ) 固定宽度函数 fixed width file
-
readHTMLTable( ) 访问网页上的数据
-
clipboard() 复制剪贴板上的内容
> x <- read.table("clipboard",header=T,sep=",")
> x
mpg.cyl.disp.hp.drat.wt.qsec.vs.am.gear.carb
1 Mazda RX4\t21\t6\t160\t110\t3.9\t2.62\t16.46\t0\t1\t4\t4
2 Mazda RX4 Wag\t21\t6\t160\t110\t3.9\t2.875\t17.02\t0\t1\t4\t4
*****************直接用↑↓切换代码,复制粘贴会变得不幸—→剪贴板改变hhh
> x <- read.table("clipboard",header=T,sep="\t") “\t”表示制表符
> x
X mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
> readClipboard() readClipboard()直接读取
[1] "\tmpg\tcyl\tdisp\thp\tdrat\twt\tqsec\tvs\tam\tgear\tcarb"
[2] "Mazda RX4\t21\t6\t160\t110\t3.9\t2.62\t16.46\t0\t1\t4\t4"
[3] "Mazda RX4 Wag\t21\t6\t160\t110\t3.9\t2.875\t17.02\t0\t1\t4\t4"
- 压缩包也可以哦 gzfile( )
> read.table(gzfile("rdata/input.txt.gz")) 输入引号后可以通过文件前几个字母+Tab快速筛选需要寻找的文件
- readLines() 以字符串形式返回每一行的数据(emm实用性?
> readLines("rdata/input.txt",n=5)
[1] "\"Ozone\" \"Solar.R\" \"Wind\" \"Temp\" \"Month\" \"Day\""
[2] "\"1\" 41 190 7.4 67 5 1"
[3] "\"2\" 36 118 8 72 5 2"
[4] "\"3\" 12 149 12.6 74 5 3"
[5] "\"4\" 18 313 11.5 62 5 4"
> scan("rdata/scan.txt",list(character(),numeric(),numeric()))
3. 访问数据库系统来获取数据
- ODBC包 Opening Database Connectivity