【R语言】--- 各类数据的导入

Python010

【R语言】--- 各类数据的导入,第1张

通常情况下,我们会在excel中对数据进行预处理,然后将处理好的数据导入R中进行分析、作图。但随着数据源和数据格式的多样化,将多种数据源和数据格式导入R中进行分析、作图显得尤为必要,因为这对于数据分析、作图是最基础的。

R可导入键盘(利用键盘输入)、文本文件、excel、access、spss、sas等各类数据格式。

利用R中的edit()函数手动输入数据的文本编辑器:

(1)创建一个空数据框(或矩阵),其中变量名和变量的模式需与理想中的最终数据集一致;

(2)针对这个数据对象调用文本编辑器,输入你的数据,并将结果保存回此数据对象中。

函数edit()事实上是在对象的一个副本上进行操作的。若不将其赋值到一个目标,则所有修改将会全部丢失!

用read.table()从带分隔符的文本文件中导入数据。此函数可读入一个表格格式的文件并将其保存为一个数据框。

参数sep允许你导入那些使用逗号以外的符号来分隔行内数据的文件。你可以使用sep="\t"读取以制表符分隔的文件。此参数的默认值为sep="",即表示分隔符可为一个或多个空格、制表符、换行符或回车符。

我习惯用readxl包的read_excel()函数进行导入:

SPSS数据集可以通过foreign包中的函数read.spss()导入到R中,也可以使用Hmisc包中的spss.get()函数。

use.value.labels=TRUE表示让函数将带有值标签的变量导入为R中水平对应相同的因子。

R中设计了若干用来导入SAS数据集的函数,包括foreign包中的read.ssd()和Hmisc包中的sas.get()。这里我们使用sas7bdat包的read.sas7bdat()函数进行导入sas数据。

Robert I. Kabacoff (著). R语言实战(高涛/肖楠/陈钢 译). 北京: 人民邮电出版社.

我的亲师弟最近也开始学习R语言了,然后师弟每天“师姐,师姐...",“我这个怎么弄...”,“我怎么又报错了...”,“师姐师姐...”...我快被他搞疯了,于是有了这篇文章。

新手在学习R语言的过程中一定会出现各种各种问题,问题多到令人抓耳挠腮。

但其实不要觉得害怕或有打退堂鼓的心里,R的使用,就是不断报错不断找问题的过程。但是出现问题,第一反应一定要是上网搜索,找答案,不要第一时间就问身边的人,错失了思考的过程。生信的学习,其实就是一个漫长的自学过程。

推荐 搜索引擎:必应,必应,必应 !不要再用某度啦拜托!当然如果你能想办法用Google,那当然再好不过了。

搜索能解决百分之九十以上的问题 ,就算解决不了,如果解决不了,可能是因为你的搜索能力还不够高。在这个搜索、尝试解决以及思考的过程,对新学者来说也是一大收获。本身搜索能力的提升就是一个巨大收获。

如果自己尝试了好久,最终实在解决不了,那。。。就再去请教有经验的前辈吧~

其实这种搜索并独立解决问题的思维,我还是在同济大学, 生信大牛刘小乐教授 课题组学到的。刘小乐教授课题组每年都有为期一个月的生信培训,本人有幸学习过一段时间。她们会给很多生信相关的题目给到学员,然后附上一些教学视频,培训的大部分时间,其实就是写作业,自己想方设法找到解决方案的过程。那些大牛师兄师姐们虽然一直在陪伴我们,但是并不会直接告诉我们答案,而是引导我们自己思考,自己去解决。当时真的很崩溃,因为真的啥也不会,怎么搞。一天下来有可能一个问题都答不上来。

但是现在回头想想,我真的获益良多。因为我慢慢学会了独立思考,现在遇到R相关的问题,配合上搜索功能,基本上已经完全能自己驾驭了。

这可能就是“ 授人以鱼不如授人以渔 ”的道理吧。

R语言很简单,只要你想学,就一定能学会。

以下附上同济大学刘小乐课题组在培训时针对初学者第一周的初级练习题。希望对大家有所帮助。

首先你需要先安装几个最常用的数据处理软件

You can use the mean() function to compute the mean of a vector like

so:

However, this does not work if the vector contains NAs:

Please use R documentation to find the mean after excluding NA's (hint: ?mean )

In this question, we will practice data manipulation using a dataset

collected by Francis Galton in 1886 on the heights of parents and their

children. This is a very famous dataset, and Galton used it to come up

with regression and correlation.

The data is available as GaltonFamilies in the HistData package.

Here, we load the data and show the first few rows. To find out more

information about the dataset, use ?GaltonFamilies .

a. Please report the height of the 10th child in the dataset.

b. What is the breakdown of male and female children in the dataset?

c. How many observations are in Galton's dataset? Please answer this

question without consulting the R help.

d. What is the mean height for the 1st child in each family?

e. Create a table showing the mean height for male and female children.

f. What was the average number of children each family had?

g. Convert the children's heights from inches to centimeters and store

it in a column called childHeight_cm in the GaltonFamilies dataset.

Show the first few rows of this dataset.

In the code above, we generate r ngroups groups of r N observations

each. In each group, we have X and Y, where X and Y are independent

normally distributed data and have 0 correlation.

a. Find the correlation between X and Y for each group, and display

the highest correlations.

Hint: since the data is quite large and your code might take a few

moments to run, you can test your code on a subset of the data first

(e.g. you can take the first 100 groups like so):

In general, this is good practice whenever you have a large dataset:

If you are writing new code and it takes a while to run on the whole

dataset, get it to work on a subset first. By running on a subset, you

can iterate faster.

However, please do run your final code on the whole dataset.

b. The highest correlation is around 0.8. Can you explain why we see

such a high correlation when X and Y are supposed to be independent and

thus uncorrelated?

Show a plot of the data for the group that had the highest correlation

you found in Problem 4.

We generate some sample data below. The data is numeric, and has 3

columns: X, Y, Z.

a. Compute the overall correlation between X and Y.

b. Make a plot showing the relationship between X and Y. Comment on

the correlation that you see.

c. Compute the correlations between X and Y for each level of Z.

d. Make a plot showing the relationship between X and Y, but this

time, color the points using the value of Z. Comment on the result,

especially any differences between this plot and the previous plot.

R语言特征:

1. type.convert()函数主要用在read.table()函数中,返回向量和因子类型,当输入为double型时会丢失精度。

>type.convert(c('abc','bcd')) # 返回因子类型

[1] abc bcd

Levels: abc bcd

>type.convert(c(as.double(1.12121221111),'1.121')) # double型丢失精度

[1] 1.121212 1.121000

2. 如果一个文件包含有小数位的数据,通过read.table()函数读取时,会指定为numeric类型。

新建一个文件num.csv包括小数

1,2,1.11

2.1,3,4.5

用read.table读取文件,并查看列的类型。

>num<-read.table(file="num.csv",sep=",") # 读文件

>num

V1 V2 V3

1 1.0 2 1.11

2 2.1 3 4.50

>class(num)

[1] "data.frame"

>class(num$V1)# 查看列的类型为numeric

[1] "numeric"

3. tools包用Rdiff()函数的参数useDiff为FALSE时,与POSIX系统的diff -b命令类似。

新建文件num2.csv

3,2,1.11

2.1,3,4.5

用Rdiff()比较两个文件num.csv和num2.csv。

>Rdiff('num.csv','num2.csv',useDiff = FALSE)

1c1

<1,2,1.11

---

>3,2,1.11

[1] 1

4. 新函数anyNA(),结果与 any(is.na(.))一致,性能更好。

>is.na(c(1, NA))

[1] FALSE TRUE

>any(is.na(c(1, NA)))

[1] TRUE

>anyNA(c(1, NA))

[1] TRUE

5. arrayInd()和which()函数增加useNames参数,用于列名的匹配。我在测试过程,不太理解这个参数的意义。

>which

function (x, arr.ind = FALSE, useNames = TRUE)

6. is.unsorted()函数支持处理原始数据的向量。

>is.unsorted(1:10) # 排序的向量

[1] FALSE

>is.unsorted(sample(1:10)) # 无序的向量

[1] TRUE

7. 用于处理table的as.data.frame()函数和as.data.frame.table()函数,支持向provideDimnames(sep,base)函数传参数。我在测试过程中,也不理解具体是什么更新。

8. uniroot()函数增加新的可选参数extendInt,允许自动扩展取值范围,并增加返回对象参数init.it。

>f1 <- function(x) (121 - x^2)/(x^2+1) # 函数f1

>f2 <- function(x) exp(-x)*(x - 12) # 函数f2

>try(uniroot(f1, c(0,10))) # 在(0,10)的区间求f1函数的根

Error in uniroot(f1, c(0, 10)) :

f() values at end points not of opposite sign

>try(uniroot(f2, c(0, 2))) # 在(0,2)的区间求f2函数的根

Error in uniroot(f2, c(0, 2)) :

f() values at end points not of opposite sign

>str(uniroot(f1, c(0,10),extendInt="yes")) # 通过extendInt参数扩大取值搜索范围

List of 5

$ root : num 11

$ f.root: num -3.63e-06

$ iter : int 12

$ init.it : int 4

$ estim.prec: num 6.1e-05

>str(uniroot(f2, c(0,2), extendInt="yes")) # 通过extendInt参数扩大取值搜索范围

List of 5

$ root : num 12

$ f.root: num 4.18e-11

$ iter : int 23

$ init.it : int 9

$ estim.prec: num 6.1e-05

9. switch(f,)函数,当参数f是因子类型时,会出警告提示,需要转换字符串参数。

>switch(ff[1], A = "I am A", B="Bb..", C=" is C")# ->"A" # 警告提示

[1] "I am A"

Warning message:

In switch(ff[1], A = "I am A", B = "Bb..", C = " is C") :

EXPR is a "factor", treated as integer.

Consider using 'switch(as.character( * ), ...)' instead.

>switch(as.character(ff[1]), A = "I am A", B="Bb..", C=" is C") # 转型为字符串处理

[1] " is C"

10. 解析器已经更新,使用更少的内存。