二. 控制流

statement:一个单独的R语句或者是一个复合的R语句;

cond:条件表达式,为TRUE或FALSE;

expr:数字或字符表达式;

seq:数字或字符串的顺序。

1.循环语句:for,while

(1)for(var in seq)  statement

for(i in 1:10)
+ print("Hello R")
[1] "Hello R"
[1] "Hello R"
[1] "Hello R"
[1] "Hello R"
[1] "Hello R"
[1] "Hello R"
[1] "Hello R"
[1] "Hello R"
[1] "Hello R"
[1] "Hello R"

(2) while(cond)  statement

> i<-10
> while(i>0) {print("Hello");i<-i-1}
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"
[1] "Hello"

2. 条件语句:if-else, ifelse, switch

(1) if-else

if(cond) statement

if(cond) statement1 else statement2

> grade<-"wang shen wen"
> grade
[1] "wang shen wen"
> if(is.character(grade)) grade<-as.factor(grade)
> grade
[1] wang shen wen
Levels: wang shen wen
> if(!is.factor(grade))
+ grade<-as.factor(grade) else
+ print("Grade already is a factor")
[1] "Grade already is a factor"

(2)ifelse

ifelse(cond,statement1,statement2)

·如果cond为TRUE,则执行ststement1;若cond为FALSE,则执行statement2.

score<-0.3
> ifelse(score>0.5,print("Passed"),print("Failed"))
[1] "Failed"
[1] "Failed"
>
> outcome<-ifelse(score>0.5,"passed","failed")
> outcome
[1] "failed"

print("Failed"):会打印两次Failed,因为第一次是Failed这个短语,第二次是print()函数自身。

(3)switch

switch(expr,...)

feelings<-c("sad","afraid")
> for(i in feelings)
+ print(
+ switch(i,
+ happy="I am gald you are happy",
+ afraid="There is nothing to fear",
+ sad="Cheer up",
+ angry="Calm down now"
+ )
+ )
[1] "Cheer up"
[1] "There is nothing to fear"

三. 用户自定义函数(user-written functions)

myfunction<-function(arg1,arg2,...){

statements

return(object)

}

例10:

定义一个函数mystat,选择参数(parameter),即平均值(mean)和方差(standard deviation);

或选择非参数(nonparametric),即中位数(median)和绝对中位差(median absolute deviation)。

> mystat<-function(x,parametric=TRUE,print=FALSE){
+ if(parametric){
+ center<-mean(x); spread<-sd(x)
+ } else{
+ center<-median(x); spread<-mad(x)
+ }
+ if(print&parametric){
+ cat("Mean=",center,"\n","SD",spread,"\n")
+ } else{
+ cat("Median=",center,"\n","MAD",spread,"\n")
+ }
+ result<-list(center=center,spread=spread)
+ return(result)
+ }
>
> set.seed(1234)
> x<-rnorm(500)
>
> y<-mystat(x)
Median= 0.0018
MAD 1
> y<-mystat(x,parametric=FALSE,print=TRUE)
Median= -0.021
MAD 1

例11:让用户选择输出日期的格式。

mydate<-function(type="long"){
+ switch(type,
+ long = format(Sys.time(),"%A %B %d %Y"),
+ short = format(Sys.time(),"%m-%d-%y"),
+ cat(type,"is not a recognized type\n")
+ )
+ }
>
> mydate("long")
[1] "星期四 八月 01 2013"
> mydate("short")
[1] "08-01-13"
> mydate("medium")
medium is not a recognized type

四. 聚合(aggregation)和重组(restructuring)

1. 反置(transpose)

使用t()函数反置一个矩阵或一个数据集,即行列的变量交换。

例12:

> cars<-mtcars[1:5,1:4]
> cars
mpg cyl disp hp
Mazda RX4 21 6 160 110
Mazda RX4 Wag 21 6 160 110
Datsun 710 23 4 108 93
Hornet 4 Drive 21 6 258 110
Hornet Sportabout 19 8 360 175
> t(cars)
Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
mpg 21 21 23 21 19
cyl 6 6 4 6 8
disp 160 160 108 258 360
hp 110 110 93 110 175

2. 聚合(aggregating)

aggregate(x,by,FUN)

·x:初始数据集;

·by:创建新观测值(observations)的变量表(lists of variables);

·FUN:使用新的观测值来,计算总的统计数据值。

例13:

options(digits=3)
> attach(mtcars)
> aggdata<-aggregate(mtcars,by=list(cyl,gear),FUN=mean,na.rm=TRUE)
> aggdata
Group.1 Group.2 mpg cyl disp hp drat wt qsec vs am gear carb
1 4 3 21.5 4 120 97 3.70 2.46 20.0 1.0 0.00 3 1.00
2 6 3 19.8 6 242 108 2.92 3.34 19.8 1.0 0.00 3 1.00
3 8 3 15.1 8 358 194 3.12 4.10 17.1 0.0 0.00 3 3.08
4 4 4 26.9 4 103 76 4.11 2.38 19.6 1.0 0.75 4 1.50
5 6 4 19.8 6 164 116 3.91 3.09 17.7 0.5 0.50 4 4.00
6 4 5 28.2 4 108 102 4.10 1.83 16.8 0.5 1.00 5 2.00
7 6 5 19.7 6 145 175 3.62 2.77 15.5 0.0 1.00 5 6.00
8 8 5 15.4 8 326 300 3.88 3.37 14.6 0.0 1.00 5 6.00

3. reshape包

在数据集的重构和聚合方面,reshape包是非常有用的。但是需要先安装,再使用,因为不是R中的基础包。

install.packages("reshape")

(1)“melt” data:是每一行是一个特别的ID变量组合(a unique ID-variable combination).

melt()函数:对一个数据集(dataset),把该数据集重构成另一种形式,每一个测量过的变量(measured variables)在其自身那行中,都有一个ID变量特别的指示着该变量。

例14:

> library(reshape)
载入需要的程辑包:plyr 载入程辑包:‘reshape’ 下列对象被屏蔽了from ‘package:plyr’: rename, round_any > md<-melt(mydata,id=(c("id","time")))
Error: id variables not found in data: id, time
> id<-c(1,1,2,2)
> time<-c(1,2,1,2)
> x1<-c(5,3,6,2)
> x2<-c(6,5,1,4)
>
> mydata<-data.frame(id,time,x1,x2)
> md<-melt(mydata,id=(c("id","time")))
> md
id time variable value
1 1 1 x1 5
2 1 2 x1 3
3 2 1 x1 6
4 2 2 x1 2
5 1 1 x2 6
6 1 2 x2 5
7 2 1 x2 1
8 2 2 x2 4

(2)“cast” the melted data:使之成为想要的形状。在cast过程中,使用函数对数据进行聚合。

cast()函数:处理melted 的数据时使用,使用一个公式(formula),提供一个可选的函数(function),去聚合函数。

newdata<-cast(md,formula,FUN)

·md:melted data;

·formula:描述期待的最终结果;

其形式为:rowvar1+rowvar2+...+colvar1+colvar2+...

rowvar1+rowvar2+...定义决定行的变量的集合;

colvar1+colvar2+...定义决定列的变量的集合。

·FUN(可选):聚合函数。

Chapter 05—Advanced data management(Part 2)的更多相关文章

  1. Chapter 05—Advanced data management(Part 1)

    一. R的数学函数,统计函数及字符处理函数 例01:一道实际应用题 一组学生其数学,科学和英语的成绩如下表: 任务:根据成绩,决定对每个学生的单独指导: 前20%的学生的成绩为A,次之为B,以此类推: ...

  2. Chapter 04—Basic Data Management

    1. 创建新的变量 variable<-expression expression:包含一组大量的操作符和函数.常用的算术操作符如下表: 例1:根据已知变量,创建新变量的三种途径 > my ...

  3. MySQL vs. MongoDB: Choosing a Data Management Solution

    原文地址:http://www.javacodegeeks.com/2015/07/mysql-vs-mongodb.html 1. Introduction It would be fair to ...

  4. 场景3 Data Management

    场景3 Data Management 数据管理 性能优化 OLTP OLAP 物化视图 :表的快照 传输表空间 :异构平台的数据迁移 星型转换 :事实表 OLTP : 在线事务处理 1. trans ...

  5. Advanced Data Structures

    Advanced Data Structures Advanced Data Structures

  6. [Windows Azure] Data Management and Business Analytics

    http://www.windowsazure.com/en-us/develop/net/fundamentals/cloud-storage/ Managing and analyzing dat ...

  7. Data Management Technology(1) -- Introduction

    1.Database concepts (1)Data & Information Information Is any kind of event that affects the stat ...

  8. Data Management and Data Management Tools

    Data Management ObjectivesBy the end o this module, you should understand the fundamentals of data m ...

  9. Building Applications with Force.com and VisualForce(Dev401)(十七):Data Management: Data management Tools

    ev401-018:Data Management: Data management ToolsModule Objectives1.List objects exposed in the impor ...

随机推荐

  1. VMware问题--无法获得 VMCI 驱动程序的版本: 句柄无效

    关于VMware问题:无法获得 VMCI 驱动程序的版本: 句柄无效.驱动程序“vmci.sys”的版本不正确 问题截图: 解决 1.根据配置文件路径找到对应的.vmx文件: 2.用编辑器打开,找到v ...

  2. 知否知否,VS Code 不止开源

    VS Code, 昨夜始于“开源”,如今“开源”深处渡. 读者看到这句话,也许会有疑惑,为什么两个“开源”都加上了双引号? 其实是笔者有意为之,因为这个两个“开源”的意义有着很大的差别,第一个“开源” ...

  3. 一个九位数-python

    有一个9位数由1~9的9个数字组成, 每个数字只能出现一次:其第一位能被1整除, 前两位能被2整除, 前三位能被3整除...依次类推,前9位能被9整除.所有的9位数中,只有一个数字满足这些条件,请你输 ...

  4. [考试反思]1001csp-s模拟测试(b):逃离

    如你所见,b组题,除了NC乱入直奔T2抢了我一个首杀以外A层学过FFT的人都没有参加. 竞争压力很小,题又简单,所以就造就了6个AK. 然而并不计入总分,我仍然稳在第二机房. T1lyl16分钟切掉我 ...

  5. 小白学 Python(18):基础文件操作

    人生苦短,我选Python 前文传送门 小白学 Python(1):开篇 小白学 Python(2):基础数据类型(上) 小白学 Python(3):基础数据类型(下) 小白学 Python(4):变 ...

  6. SpringBoot整合Swagger实战

    源码地址:https://github.com/laolunsi/spring-boot-examples 目前SpringBoot常被用于开发Java Web应用,特别是前后端分离项目.为方便前后端 ...

  7. T1

    老师的作业提示里说有难题,也有水题,果真很水... 单纯的模拟加暴力 #include<iostream> using namespace std; int n; ; int cow[ma ...

  8. layui多级弹框去掉遮罩

    var index = layer.open({ type:1, title:'请选择费用代码', area:['1050px','650px'], content:$('#selectFee'), ...

  9. PHP读取Excel内的图片

    今天接到了一个从Excel内读取图片的需求,在网上查找了一些资料,基本实现了自己的需求,不过由于查到的一些代码比较久远,不能直接移植到自己的项目里,需要稍加改动一下. 这里介绍一下分别使用phpspr ...

  10. ASP.NET Core 1.0: Deploy to IIS

    尽管ASP.NET最新的官方文档记录了如何Deploy to IIS,但是实际操作起来依旧磕磕绊绊.官方文档地址:https://docs.asp.net/en/latest/publishing/i ...