R language ︱ function usage tips (loops, if family/for, switch, repeat, IfElse, stopifnot)

Source: Internet
Author: User
Tags exception handling numeric



Often thought to climb the mountains small, can, often and actually come to the beginning, Daniel, slowly step to my notes PA share it, please~

———————————————————————————

Follow-up add more content:

Application One: What are the members of the If family? --if/ifelse/stopifnot Application Two: How to consume real time output in the loop.

————————————————————————————————————


1. Circulation

# #循环for
Iris
allzl=unique (iris$setosa)
for (i in 1:2) {
  pp=iris[iris$setosa==allzl[i],]
  plot ( Pp$sepal.length~pp$sepal.width)
}


For loop, you need to combine the numbers, if the data neatly can be used matrix, if not neat, with the list, unequal length of the merger, the Rbind.fill function can be very good to merge the data, and do not match the missing value is NA.

Refer to: R language ︱list usage, bulk read, write Data


Case

Temp<-matrix (data = na,181,31) for
(i in 1:31) {
  Temp[,i]<-filter (DATA[I]/7, Rep (1, 7))
  }
Yatmdata<-data.frame (temp)
The code uses the matrix to define a 181*31 null matrix, and then pour the numbers inside.


2. Switch Branch statement

# #switch分支语句
switch (1,mean (1:10), Rnorm (4))  #执行mean (1:10)
switch (2,mean (1:10), Rnorm (4))  # Execute Rnorm (4)
#由switch (x) to choose to execute that function

3. While loop statement

Note The order of execution, first execute f[i]+f[i+1]<1000, then go down, with the following repeat difference

# #while循环语句
#计算斐波那契数列
f=1
f[2]=1
i=1 while
(f[i]+f[i+1]<1000) {
  f[i+2]=f[i]+f[i+ 1]
  i=i+1
}
F
#注意执行顺序, perform f[i]+f[i+1]<1000 first, then go down, with the following repeat difference


4. Repeat cycle

Often associated with If.

# #repeat语句
#计算斐波那契数列
f=1
f[2]=1
i=1
repeat{
  f[i+2]=f[i]+f[i+1]
  i=i+1
  if (f[i]+f [i+1]>1000] Break
};f
#与if常常联用, note the order of execution, f[i]+f[i+1]>1000, unlike while<1000

Often associated with if, note the order of execution, f[i]+f[i+1]>1000, unlike while<1000.


5. If function +function

If and while are logical type variables that require data true/false, which means that the if interior is often judged on the condition, such as Is.na, Is.matrix, Is.numeric, and so on, or a comparison of size, such as if (X > 0), if (x = = 1), if (length (x) = = 3) and so on.

If after, if it is 1 lines, the curly braces can be omitted, otherwise you have to put all the statements in curly braces. This is consistent with the loop.

Fun.test <-function (A, B, method = "Add") {
    if (method = = "Add") {# # if or for/while;
        Res <-A + b       # # etc Polygon is only one row, you do not need to use curly braces.
}
    if (method = = "Subtract") {
        res <-
    A-B}
    return (res)           # # return value
}
# # # test Result
fun.test (a = 10, B = 8, method = "Add")
fun.test (a = ten, B = 8, method = "Substract")


At the same time if there is a similar use with Excel--ifelse

IfElse (age >, ' old ', ' young ')

Age variable >30, output old;<30, output young


————————————————————————————————————————————————————————————

A practical case of combining function and cyclic functions


1, how the function output. --print, Return&list


If it is a single output, you can use the 1.3 method directly

If there are many output items, then you need to return (terminate the operation and output the project in return) to the final output of the project

The default in R is to use the last sentence as the return value.


1.1 Return&list Combination


The combination of return and list output is quite reasonable. (from R language ︱ noise data processing, data grouping--binning method (discretization, hierarchical))

[HTML]  View plain  copy  print? Sbdeep=function (data,parts,xiaoz) {     parts<-parts           #分几个箱      xiaoz<-xiaoz           #极小值        value<-quantile (Data,probs = seq (0,1,1/parts))    #这里以data等比分为4段, step 1/4     number<-mapply (function (x) {        for  (i in 1: (parts-1))         {         if (x>= (value[i]-xiaoz) &x<value[i+1])           {           return (i)          }       }        if (X+xiaoz>value[parts])        {         return (Parts)        }        return ( -1)      },data)       #打标签L1L2L3L4       Return (List (Degree=paste ("L", number,sep= ""), degreevalue=number,value=table (value), number=table (number))                  #将连续变量转化成定序变量, at this time for L1,l2,l3, L4 ... According to parts  }   This function is a class-deep sub-box for a single sequence of data, which can be returned in four categories:

One based on l1l2l3 .... The label sequence of each indicator degree;

Tag sequence value Degreevalue,

The value of the variable that corresponds to each percentile,

Number of different percentage points.


1.2 Print Direct output

  function () {
    print (cv.out) 
  }

Print can be output directly.


1.3 Direct output--a general direct output

function () {
a=c (1:50)
a
}
Where a is written directly at the end, as an output item.


2. Use the IF switch function in function


Test=function (Mode=c ("All", "out", "on")) {
  mode <-switch (mode, out = 1, ' in ' = 2, all = 3)
 
  if (as.numeric (mode ==1) {
    t=1
  }
 
  if (as.numeric (mode) ==2) {
    t=2
  }
 
  if (as.numeric (mode) ==3) {
    t=3
  }
  t=t+1
  return (t+4)
}
a=test (mode= "out")

test (mode= ' in ')

test (mode= "all")
Solution Scenario: When writing a function, it may be necessary to use this process when it is possible to nest many models.

Switch function, enter mode, execute the corresponding content, this is mode select "All", then the execution return 1,;mode select "Out" returns 2;

Then use if to do the modeling behind each number, note the "= ="
"In" note the quotation marks, because they overlap with inline functions


3 Outlier Handling--How to error

  # exception handling, when only one data is entered, the notification cannot calculate the standard deviation
   if (length (x) = = 1) {                          
      Stop ("Can not compute SD for one number,
           a numeric vector required.\n ")       
   }


———————————————————————————————————— Apply one: What are the members of the If family? --if/ifelse/stopifnot


In a function, if is used in many scenarios to identify a class of situations and then perform the next.

The author has seen such a class of three If:if-else IfElse Stopifnot


1, If-else


This is very common, it is necessary to pay attention to the wording of the if-else, to see the management of the Home forum a friend of the reminder and use experience:


if () {}else{} means that the conditional statement after the IF bracket is executed first, if the program in the first curly brace is executed correctly, if the error executes the statement in the curly brace after the else.
In one case, R will error:

if () {}

In this case, when the Else statement is executed in a row, it is r that the IF statement has been executed, but the Execute else discovery cannot be performed before, so an error occurs, where the comrades using R are reminded that the else must be next to the curly braces after the IF statement, and then there will be no error.


2, IfElse


It's exactly the same as If-else, but with a lot more efficiency, it's a very efficient function to improve the code. The syntactic format of IfElse () is similar to the if () function, but its operation speed has been greatly improved. Even if there is no pre-defined data structure and there is no simplified conditional statement, its operation efficiency is higher than the above two methods.

IfElse (test, yes, no)

IfElse return is the result, a little trouble is, unlike If-else, can write some of the distribution of computing things, such as now have one of the following:

A<-c+d
sum (a>2)  #在c大于2的情况下, to calculate the number of a greater than 2

This step is a good solution in the if-else, but in IfElse it is not easy, can only accept one step, so try to combine the chain of operations.


3, Stopifnot


This function is a bit like ifelse, but it's very peculiar. Stopifnot (C>2), if the correct execution, then nothing will happen, if wrong, will jump into the debug mode, error, let the function immediately stop.

This stopifnot, combined with the Trycatch function, is incredibly powerful.


Skip with Trycatch:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.