R语言基础Lecture3

上节课list的补充

> x = matrix(1:20, nrow=5, ncol=4, byrow=TRUE)
> swim = read.csv("http://www.macalester.edu/~kaplan/ISM/datasets/swim100m.csv")
> mylist=list(swim,x)
> mylist[2]#返回list的第二部分内容
[[1]]
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
[4,]   13   14   15   16
[5,]   17   18   19   20

#第几部分为[[]]
> mylist[[2]][2]#返回list第二部分的第二个元素,默认按列
[1] 5
> mylist[[2]][1:2]#返回list第二部分的第一和二个元素,默认按列
[1] 1 5
> mylist[[2]][1:2,3]#返回list第二部分的第一和二行的第三列
[1] 3 7
> mylist[[2]][1:2,]#返回list第二部分的第一和二行所有元素
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8

基本操作

>, >=, <, <=, ==, !=, x | y, x & y

控制流

循环语句

尽量避免使用For-Loop和While-Loop

> #For-Loop 
> for(i in 1:10){
+   print(i)
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

> #While-Loop 
> i = 1
> while(i <= 10)
+ {
+   print(i)
+   i=i+1
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

条件语句

If statement、If-else statement和switch
switch语法:switch(expression, conditions)

> i = 1
> if(i == 1){
+   print("Hello World")
+ }
[1] "Hello World"
> i = 2
> if(i == 1){
+   print("Hello World!")
+ }else{
+   print("Goodbye World!")
+ }
[1] "Goodbye World!"
> feelings = c("sad", "afraid")
> for (i in feelings){
+   print(
+     switch(i,
+            happy = "I am glad 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"

自定义函数

如果function要写return要带()
curve第一个参数为一个function

> myfunction = function(x,a,b,c){
+   return(a*sin(x)^2 - b*x + c)
+ }
> curve(myfunction(x,20,3,4),xlim=c(1,20))

在这里插入图片描述

> curve(exp(x),xlim=c(1,20))

在这里插入图片描述

> myfeeling = function(x){
+   for (i in x){
+     print(
+       switch(i,
+              happy = "I am glad you are happy",
+              afraid = "There is nothing to fear",
+              sad = "Cheer up",
+              angry = "Calm down now"
+              )
+         )
+     }
+ }
> feelings = c("sad", "afraid")
> myfeeling(feelings)
[1] "Cheer up"
[1] "There is nothing to fear"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值