If fact, I already used "for" statement to make a simple function last post.
Today I will introduce two more classic control statement "while" "if"
First let's review the function we made last post.
Addyourdata <- function (x, N) {
for (j in 1:N) {
j=j+1
x=x+1
}
return(x)
}
As you can see, for statement is used to control iteration and another representative iteration statement is "while"
Let's look at the below
Addyourdata_w <- function (x, N) {
j=0
while (j<N) {
j=j+1
x=x+1
}
return(x)
}
Two functions lead to same result. It's up to you what iteration statement do you use for your program. why don't we compare the result
> data <- c(1,2,3,4,5,6,7,8,9,10)
> Addyourdata (data,11)
[1] 12 13 14 15 16 17 18 19 20 21
> Addyourdata_w (data,11)
[1] 13 14 15 16 17 18 19 20 21 22
>
Lastly, If statement is also commonly used to control any program.
Let's assume that input variable "N" of above function should be more that 10
and if anyone try to execute this function with variable "N" is under 10, display any message.
your expected code is similar to below.
Addyourdata_if <- function (x, N) {
j=0
if (N>=10) {
for (j in 1:N) {
j=j+1
x=x+1
}
}
else {
return("Please assign number more than 10")
}
return(x)
}
Results are.
Check the message.
> Addyourdata_if (data,5)
[1] "Please assign number more than 10"
> Addyourdata_if (data,8)
[1] "Please assign number more than 10"
> Addyourdata_if (data,9)
[1] "Please assign number more than 10"
> Addyourdata_if (data,10)
[1] 11 12 13 14 15 16 17 18 19 20
> Addyourdata_if (data,23)
[1] 24 25 26 27 28 29 30 31 32 33
>
Done.
댓글 없음:
댓글 쓰기