本文编辑版本:R version 3.5.0
一、 循环for while语句
回顾R中的数据结构,假设:
1x <- c(5, 2, 6, 8, 4, 2)
这是一个简单求和然后求均值的问题,对于一个vector,求每个数的总和,你可以简单地写出: sum(x)/n 或者mean(x)来求均值(没人会说这不行)。当然为了教学,我想在这里引出循环来解决这个问题:
1
2
3
4
5
6
7
8
9
10
11
12
13
14n <- length(x) sum.x <- 0 for(i in 1:n){ # loop repeated n times # compute cumulative sum sum.x <- sum.x + x[i] print(i) # print index value in each iteration (for debugging) } # end for loop # compute average sum.x/n
for loop里面的i,只是一个代号,你可以把它换成m、n之类的未被定义的字符,效果是一样的(但是我不推荐)。同时,你也可以使用while loop来解决这个问题:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16# average the numbers in vector x using a while() loop sum.x <- 0 index <- 1 # set index n <- length(x) while(index <= n){ # loop repeated as long as index # is less than or equal to n # compute cumulative sum sum.x <- sum.x + x[index] print(index) # print index value (for debugging) # increase index index <- index+1 } # end while loop
二、逻辑符号
再介绍一些逻辑符号,大家可以自己尝试效果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18############################## # logical operators table # ############################## x <- 5 y <- c(7,4,2) z <- c("a","b","c") !(x > 4) x == 4 z == "c" x != 4 (x>4) & (x<=10) (x>4) | (x==6) any(y==2) all(x==3) is.element(x,y) x%in%y
3、条件语句
1
2
3
4
5
6
7
8
9# Try the following: x <- 145 if(x/3 > 10){ print("Yes!") }else{ print("No") } # end if/else
最终,这会输出为“Yes!”。如果我们要求一个vector的中位数,我们可以简单地median(x),不过我们也可以使用条件语句:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19################################# # measures of center: median # ################################# x <- c(1, 3, 5, 2, 7) n <- length(x) if(n%%2==0){ # n is even median.x <- sum(sort(x, decreasing=FALSE)[(n/2):(n/2+1)])/2 }else{ # n is odd median.x <- sort(x, decreasing=FALSE)[ceiling(n/2)] } # end if/else median.x # verify with R functions median(x) quantile(x, probs=0.5)
Cool right? 只需要简单地学习一些符号和逻辑,我们便可以自己定义中位数,均值地方程了。 只要你愿意,你也可以尝试计算x的方差, 标准差。 不如自己动手尝试一下?如果X里面还有NA项呢?我们的语句(试试while)需要调整吗?该如何调整?
KEEP IN MIND:
You will not break your computer: when in doubt, just run your code and see what happens;
Test small portions of your code at a time to remove errors;
Comment your code LIBERALLY so you remember what you have written;
Help pages are very helpful;
For longer programs, write a draft of your code in English before translating it into R code; (i.e., write a template)
To stop running code press the Escape key (on a Mac);
There is almost alway more than one way of writing a piece of code.
试试这些些题目,看看能不能很快做出来:
最后
以上就是魔幻皮带最近收集整理的关于R语言入门教学(5)- For while if/else 以及逻辑符号的全部内容,更多相关R语言入门教学(5)-内容请搜索靠谱客的其他文章。
发表评论 取消回复