top of page
All Posts: Blog2

# [Research] R Basics 3- Basic Coding in R

In languages such as C++ or python, the ifelse and for commands are much straightforward. However, in the case of R, one accustomed to using C++ or Python might feel slightly different as R does not have to declare the index of a list or a vector. However, we can still use the functions ifelse and function(){} to code basic loops.

ifelse is one of the basic forms of a logical statement, and the basic form is (conditional, if true, if false). We can use a simple code as the following to obtain the reciprocal of positive numbers.

```ifelse(a>0 , 1/a, NA)
a<- c(0,1,2,-4,5)```

function is also an incredibly useful tool in R coding; we can use the following code to obtain the mean of a vector. Note that the variable is declared inside function(x) and the function itself is coded within the curly brackets.

```avg<- function(x){
s<-sum(x)
n<-length(x)
s/n
}```

We can use the same method to code a function that adds 1 to n.

```compute_s_n <- function(n){
x<- 1:n
sum(x)
}```

When we apply this, we can use the code below which will give us 55.

`compute_s_n(10)`

But if we wanted to know each of the sums of 1 to a number smaller or equal to 10, we can use the sapply() function as the following.

```n <- c(1:10)
sapply(compute_s_n, n)```

An alternative way of doing so may be creating an empty vector and inserting each of the values in the vector. For those who are more used to C++ or Python, this method may seem more intuitive.

```#create an empty vector
s_n <- vector(length=m)
for (n in 1:m){
s_n[n] <- compute_s_n(n)
}```

We can plot the result using ggplot() with n=1:100, and the parabola confirms that we have made the right code. 1 view

See All
bottom of page