Saturday, April 29, 2023

R Tutorial Playlist - String Operations

 In order to operate with strings in R, you need library stringr for that purpose, so the very first line in your code should be:

library("stringr")

R provides a lot of functions for string manipulations.

Purpose of function word is to retrieve word from string based on index of that particular word.

word(a, b)

  • a is string that we are going to search through
  • b is index of word in string a we want to retrieve as result
Function str_length is going to return length of provided string.
str_length(a)
  • a is string that we want to receive length as result
Function str_locate is going to return beginning and ending index of word provided as second argument.
str_locate(a, b)
  • a is string that we want to search through.
  • b is word we want to look for.
  • result of this function is array of two numbers; one for the beginning index of word b and second is ending index of word b.
Purpose of function str_sub is to return substring. 
str_sub(a, b, d)
  • a is string we want to search through for the substring.
  • b is staring index of substring we want to receive as result.
  • d in ending index of substring we want to receive as result.
Function str_count is going to return number of occurrences of word we are searching for.
str_count(a, b)
  • a is string we want to search through.
  • b is string that we want to search for occurrences.
Function str_to_upper is going to return string with all upper letters.
str_to_upper(a)
  • a is string that we want to turn all of letters into upper letters. String with all upper letters is going to be provided as result of this function.
Function str_split is going to split provided string by splitting pattern.
str_split(a, b)
  • a is string we want to split
  • b is splitting patter written in regular expression.
Function str_c is going to add two strings together.
str_c(a, b, sep="")
  • a is string that is going to be appended to.
  • b is appending string.
  • sep is string that is going to be inserted in between a and b.
Function str_remove is going to remove substring from main string.
str_remove(a, b)
  • a is string that is going to be removed from.
  • b i string that is going to be removed.
Both functions str_replace and str_replace_all are going to replace substrings from main string. First of those two is going to replace only the first occurrence of substring, and second is going to replace every occurrence of substring. 
str_replace(a, b, d)
str_replace_all(a, b, d)
  • a i string that is going to be replaced from.
  • b is string for replacement that is a substring of string a.
  • d is string that is going to replace substring b in string a.

For video tutorial, check the link below.


R Tutorial Playlist - Random values

Don't forget that there is no such a thing as random value in computer technology. With random number generating functions we are actually getting numbers that look random from human perspective. Those numbers are created using complex calculations with computer time as the base or seed value. R has multiple functions for that purpose.

 runif(a, b, d)

  • a is number of results we want to receive from this function
  • b is bottom limit
  • d is upper limit
This function return floating point numbers, so if you want integer results, wrap this with as.integer() function.

fnorm(a, b, d)

  • a is number of results we want to receive from this function
  • b is mean value, means value that is going to be central point around which rest of values are going to revolve.
  • d is standard deviation, means how far from mean value our values can step away.
seed(a)

If you use seed function, and provide some number as argument, you are going to receive from that moment on, all the same values from random functions. Function seed, overrides regular behavior of random number generating functions. When you use it, from that moment, seed or source value for calculations is not going to be computer time any more, but value you have provided as argument.

sample(c(...), b)

  • c(...) is collection of elements from where this function is going to pick results.
  • b is number of how many elements we want to retrieve from function sample.

For video tutorial, check the link below


Wednesday, April 26, 2023

R Tutorial Playlist - printf and sprintf

 Functions printf and sprintf are borrowed from c programming language and you need R.utils package imported in order to use them.

Both those functions require format string where, with %s function requests string as argument, with %d- number, %f- number with floating point, and with %x argument is going to be interpreted as byte and presented in hexadecimal format.

printf("%s\t%d\t%x\t%.3f", "hey", 12, 10, 25.2698)

Result from printing function above is going to be:

hey    12    a    25.269

With formatting string with %s we demanded that our first argument must be a string, and string that we provided is "hey". With \t we are telling that we need 4 empty spaces in between our arguments. Then with %d we demanded integer and we provided 12 to it. Next was %x and we provided 10; however a is printed; that is because a is 10 in hexadecimal form. Finally instead of 25.2698 that we provided as final argument, 25.269 is printed; because with formatting argument of %.3f we said that we need floating point number with 3 decimal places, so fourth decimal place is ignored.

Function sprintf does the same as function printf, but instead of printing resulting string to the screen, result is assigned to a variable.

a <- sprintf("%s\t%d\t%x\t%.3f", "hey", 12, 10, 25.2698)


For video tutorial, check the link below:



R Tutorial Playlist - Suppress warnings and messages

With function: 

suppressMessages()

you are going to suppress all of warning and other kinds of messages from the code you are going to provide as argument to this function.


For video tutorial, check the link below.




R Tutorial Playlist - Console output

 There are multiple functions in R with the purpose of providing textual output.

  • print("text to be printed") is the most common way to print value out. This function treats provided text as an array and doesn't provide any formatting.
  • cat("text\n", file="path", append= TRUE) this function provides great formatting + if you provide optional argument file, text from the first argument is going to be printed to selected file, else text is going to be printed to the screen. If you set optional argument append to TRUE, text from the first argument is not going to replace content of the file.
  • printf("%s", "hey") this function works in the same way like in c programming language, and I will talk about it in upcoming episodes. For this function package R.utils must be imported.
  • message("text") the best solution for most of cases when you need user output. Provides formatting.
  • warning("text") same as message but it states that this message is actual warning.
  • stop("text") same as message but unlike warning, this function is going to print text to the screen and then to terminate script.


For the video tutorial, check the link below.



R Tutorial Playlist- Environment variables

In the first line, we are creating regular variable 

a <- 13

And now, let's create environment variable.

b <- new.env()

If we use function ls(), we are going to receive list of all variables in our session, and we are going to see that both of this variables are present.

Where is the main difference in between regular and environment variables in R? With environment variables you can assign multiple values to a single variable.

b$first <- "value"

b$second <- 17

In this case, we have created two sub variables under environment variable b, and in order to use those sub-variables, we are going to call them from environment variable b like:

message(b$second)

So, in order to access value withing environment variable we are going to use environment variable name, then $  and sub-variable name at the end.

Finally, if we want to delete environment variable from our session, we can do that in the same way like with any regular variable.

rm( b)


For video tutorial, check the link below.



R Tutorial Playlist - User input

In order to use user input, you need executable script and in case of Linux OS, you are going to provide line 

#!/usr/bin/Rscript

at the beginning of your code, and in file properties check executable.

Line that reads actual input is:

a <- readLines(file("stdin"), 1L)

Function readLines accepts argument file("stdin") that is actual standard input, and second argument 1L means that we are going to read only one input line.

Then you can just print your input to the screen like:

message( paste("This is our input: \n", a))

For video tutorial, please check the link below.



Monday, April 24, 2023

R Tutorial Playlist - Functions

Functions are basically pieces of code that you can call from your script repeatedly. But those pieces of code can accept different values in the form of arguments. This is how one simple function definition would look like: 

a <- function('list of arguments'){

    'statement to be executed'

}

If you want to provide known number of arguments to the function, do it in this way:

function(a, b, d, e)

In this case, all of arguments provided are mandatory to this function call.

If you want to provide optional arguments, here is the way

function(firs="some value", second= 13, third= FALSE)

Arguments where you use = to assign value, are not mandatory. You can declare as many you want during function declaration, but during function call, you don't have to provide a single one.

If you want to provide unknown number of arguments to the function you can do it in this way

function(...) 

Than, in order to access those arguments, you need statement 

args <-list(...)

where args is variable of type list that holds all of those arguments you have provided.

And finally, you can combine mandatory arguments, unknown number of arguments and optional arguments in the same function call. Definition for that function would look like this.

function(a, b, d, ..., first=" hey")

During function call in this case, you must provide 3 mandatory arguments first, then you can have as many arguments you want that are part of the list(...), and argument first is optional, but if you don't provide value for argument first, that argument is going to hold default value that we have provided during function definition "hey"

If you want function that returns some value, in function scope, you will have to provide return statement as the last line of that scope.

a <- function(){

    return('value to be returned')

}


Video tutorial link below.



Saturday, April 22, 2023

R Tutorial Playlist - Code in scopes

 Unlike many other programming languages, R doesn't treat variables in scopes in the same way. If you take Java or C for example, if some variable is declared in local scope, it can't be used outside of it. Usually, when process from within the scope is over, variable is deleted from memory, or in case of java prepared for deletion.

R doesn't have that kind of limitation. You can declare variable in one scope and use it in another; it's totally fine. The only way to prevent that is to perform variable deletion at the end of scope where it's created, with function rm(), where name of the variable is going to be provided as the first and only argument.


For video tutorial, check the link below.



R Tutorial Playlist - Error handler, try catch statement

Try catch statement in R is function that is going to help you to preserve process flow even if something unexpected like error happens. So, even if your execution runs on error, your code is not going to crash. 

tryCatch(

    {

        "17" / 8

    },

    warning= function(w){

        print(w)

    },

    error= function(e){

        print(e)

    },

    finally={

        print("anyway")

    }

)

First argument of this function is, actual, problematic code, or code that could produce an error. With warning argument, we are able to provide response on warnings where argument w is actual textual representation of warning itself. Unlike errors, warnings are not going to crash your code.

Argument error provides function that is going to be executed if error happens, where e is actual textual representation of error itself.

And statement provided with argument finally is going to be executed anyway.


Check video link below.



R Tutorial Playlist - Nested loops

 Nested loops are usual feature of almost every programming language. This feature allows you to nest one loop inside of the another.

a <- list(b=c(1,2,3), d=c(2,3,4))

for(i in a){

    for(ii in i){

        if(ii%%2==0){

            message(ii)

        }

    }

}

In this case, we have list a with two collections. With first for loop, we are iterating through collections of list a; with second for loop, we are iterating through elements of collection we are passing through with first for loop. Finally we are checking if element we are passing through is odd or even, and if it's even, we are printing it to the screen. In this way, we have utilized two for loops and one if loop in the same statement.

Check video below.



R Tutorial Playlist - Repeat loop

 Repeat loop in R have exact the same purpose as while loop, just without condition statement. Repeat loop is as while loop with condition TRUE. This loop would run indefinitely, unless we provide command break to stop it.

repeat{

    'process'

}

Video tutorial link below.



R Tutorial Playlist - While loop

 While loop is used in cases when you have to iterate through some process unknown number of times.

while(TRUE){

    'process'

}

or

while(a>10){

    'process'

}

In the first case, condition is TRUE, so this loop would run indefinitely unless we provide command break in its process scope. In second case, we have statement as condition; now, you can provide any statement in  between condition brackets as long its product is TRUE or FALSE.

Finally, this loop is going to run as long condition that keeps it running is TRUE.

For video tutorial, check the link below.



Friday, April 21, 2023

R Tutorial Playlist - For loop

For loop is irreplaceable feature of R programming language, and many other languages for that matter. It's design for iteration through a list of known number of elements.


for(i in c(1:10)){

    message(i)

}

In this case, c(1: 10) is holding integers from 1 to 10. In first iteration, i is going to be 1, and in every next iteration i is going to take next value from the collection.


for(i in c(1, 2, 3)){

    message(i)

}

In second case, c(1, 2, 3) holds three elements 1, 2 and 3. In first iterations i is going to hold value of 1 in second 2 and at the end 3. So, element from the collection per iteration.


a <- c(1,2,3,4,5)

for(i in c(1:length(a))){

    message(a[i])

}

Now, we are taking different approach. We are not iterating through collection a itself but through the collection of integer numbers from 1 to the number of elements of collection a. For that reason, to function message, we have to provide collection a and i as index that we are iterating through.


a <- c(1:10)[c(TRUE, FALSE)]

for(i in a){

    message(i)

}

Now statement [c(TRUE, FALSE)] is going to populate collection a with every odd number in between 1 and 10.


Video tutorial link below.



Tuesday, April 18, 2023

R Tutorial Playlist - Switch case

 Switch Case statement is designed to serve the same purpose as If Else statement but with focus on cases with bigger number of conditions. There is no actual limit where you should stop using one and start using another; it's on every developer to decide that for himself.

a <- 2

switch(

    a,

    print("1"),

    print("2"),

    print("3")

)

As you can see, switch case statement in R is functions where first argument is value that is going to be tested. In our case value a is holding numeric value of 2. R checks value stored in first argument and then it executes statement with that index. Indexing is started from 1, from second argument provided to switch function. 

a <-"2"

switch(

    a,

    "1"= print("1"),

    "2"= print("2"),

    "3"= print("3")

)

In second case, a holds textual value. Now, every statement checks is the value at the beginning of every statement equals to value holded by variable a. If it is, that statement is going to be executed.

Check video tutorial below.



Monday, April 17, 2023

R Tutorial Playlist - If else, ifelse

 Whit this episode, we are starting with flow control subject, and the first flow control mechanism we are going to cover is if else statement.

if(a>10){

    'statement a'

}else if(a=10){

    'statement b'

}else{

    'statement c'

}

With if(a>10) we are making first condition. If a>10 is true, 'statement a' is going to be executed, if is not, execution is jumping to second condition. Second and every other condition, except first one, goes with else if keyword. If second condition is true, 'statement b' is going to be executed, else 'statement c' is going to be executed. Every execution statement must be in within scopes {}.

There is one more way to use if else loop and that is with function:

ifelse('first condition', 'statement a', 'statement b')

First argument is actual condition, second is statement that is going to be executed if condition is true and third argument is statement that is going to be executed if condition is false.

In this episode, we covered one more subject and that is function invisible(). This function is going to prevent printing of every statement provided as the argument.

Video tutorial link, below:



Sunday, April 16, 2023

R Tutorial Playlist- Search Through Data Frame

 R provided us with the way to search through data frame in similar fashion like with databases. Basically, you can provide some search criteria and get data out of data frame based on that very same criteria you have provided.

If we have data frame like this one:

data <- data.frame(names=c("John", "Steve", "Mick", "Brian"), age= c(14,19,25,20))

If we want to search for person whose age is greater than 19, we could do something like this:

data$name[data$age > 19]

What is happening in here? data$name means that we are going to search through data frame called data through column name. Condition for this search is within angle brackets. We are searching for those elements of column name whose value for age is greater than 19.

The only new thing in here is $. This symbol is used to split object that holds data from its elements; like in this case data frame and its column.

But not only that you can provide single search criteria, you could provide multiple in this form:

data$name[data$age>10 & data$age<20]

You can get result from multiple of columns if you want. Check this one:

c(data$name, data$age)[data$age>10 & data$age<20]

Now, we are going to receive result from both columns.

For video tutorial, link below.



Saturday, April 15, 2023

R Tutorial Playlist - Data Frame

 Data frames and matrices are very similar types of arrays. While with matrices you are limited to single type of data per entire matrix, with data frames you still have that limitation enforced only at columns. So frame can't contain different types of data within single column, but you can have different types of columns within the same data frame. So, if matrices are designed for the purpose of calculations, data frames are designed for the purpose of presentations.

a <- data.frame(names=c("Leo", "Mickey", "Donie"), age=c(25, 17, 31))

As you can see, declarations of data frame is quite simple. To data.frame function, you have to provide collections of data, that are going to be presented as columns.

For video tutorial check the link below.



Thursday, April 13, 2023

R Tutorial Playlist - Matrix

 Matrices in R are just like those in mathematics; tables of numerical values, that you can do calculations with. In order to create matrix you have to call function matrix like:

m <- matrix(c(2, 7, 9, 12, 19, 6),  ncol= 2, byrow= TRUE, dimnames= list(c("I", "II"), c("1", "2")))

So, with function matrix, we are going to assign our new matrix to variable m. With first argument, we are providing actual values to our matrix. ncol stands for number of columns. With byrow set to TRUE, values from vector we have provided in our first argument, are going to be arranged by rows; so in regards that we have two columns set, our first row is going to contain values 2 and 7, second row 9 and 12 and so on... If we set byrow to FALSE, our first row would have values of 2 and 12, second 7 and 19... Optional argument dimnames accepts list as value and that list contains two vectors with textual values; firs vector contains names for rows, and second vector names for columns.

Now, in order to perform mathematical operations with two matrices, those two must be of equal number of rows and of equal number of columns. So, we are going to take our m matrix for this purpose.

m * m  or  m ^ 2 is going to produce new matrix that is going to hold every element of m matrix multiplied by itself.

m * 0.78 is going to produce new matrix with every element of matrix m multiplied my 0.78.

In order to get elements from matrix, we have to use slicing, same as with vectors and lists.

m[1, 3] in this case, we are going to select value from the first row and the third column.

Keep in mind that in R, indexing starts with 1 and with slicing in angle brackets, first we select rows and then columns.

m[c(1, 3), c(1, 4)] in this case we are going to select values from first and third row and from first and fourth column.

m[-3, -1] in this case, we are going to select all of values from m matrix except those from entire third row and entire first column.

m[, 3] if we exclude some part like in this case, we have provided empty place for rows, this means that we are going to select all of rows but only from third column.

m[2:3, 3:4] in this way, we are going to provide range of values, from second to third rows and from third to fourth column.

If we want to add additional column, we are going to use function cbind, but keep in mind that we must provide right number of elements. So if our matrix contains 3 rows, we can't add 4 elements in new column. Same rule applies with rows and in order to add additional row, we are going to use function rbind.

m <- cbind(25, 17, 92)

m <- rbind(5, 76, 13)

You noticed that we provided 3 elements with rbind function, and that is because with previous line we added one more column to our matrix, so now we must provide 3 elements in row in order for everything to work in proper way.

Now we are going to end with matrix 4 x 3, and in this case, the last row and the last column are not going to be properly named. In order to solve that, we are going to use functions.

colnames(m) <- c(".", "..", "...")

rownames(m) <- c("1", "2", "3", "4")


For video tutorial, link below:

R Tutorial Playlist - Factors

 Factors in R are like vectors, but with one more attribute. If you turn some vector into factor, it's going to preserve elements, but it's going to get additional collection of elements in it, called levels. Levels are basically unique element from that vector. A top of all of that, we could provide optional parameter to function factor, called levels that accepts vector as value and in that vector, we are going to arrange levels in order we prefer.

a <- c("m", "m", "f", "m")

b <- factor(a, levels= c("m", "f"))

Video tutorial link below:



R Tutorial Playlist - Structure

 Structure in R is the way to provide some attribute to a list or a vector or to change their behavior.

a <- structure(list(names=c("John", "Mick"), age=c(25, 29)), type= "people")

In this way we are going to create structure that is going to contain list that contains two vectors named "names" and "age", and one attribute called "type". We can get data from those vectors in the same way like with any lists, but in order to get attribute value we have to use function attr like attr(a, "type"). Function attr requares two parameters; first is the structure name, and the second is name of attribute we want to get.

If you want to change behavior of a list, you can do that in next way:

a <- structure(list(names=c("John", "Mick"), age=c(25, 29)), class="data.frame", .Names=c("names", "age"), row.names= c("1", "2")) 

Class attribute is going to change behavior of list a to that of data.frame. With argument .Names we are going to set names for our columns, and with argument row.names, we are going to set names for our rows.

Video tutorial link below:

R Tutorial Playlist - List

 Lists are arrays in R but unlike vectors, lists can hold other lists and vectors.

a <- list()

a <- append(a, 1)

a <- append(a, "a")

a <- append(a, FALSE)

In the first line, we've declared list a, and in next three lines, we have appended elements of different types to it. Now, if you want to call some element from this list, you will have to provide this kind of call a[[1]], so we are calling first element from list a. In case of single element with lists, we have to provide this double angle bracket symbols.

In next example, we are going to create a list that is going to contain two vectors:

a <- list(a= c(1, 2, 3), b= c("a", "b", "c"))

Now, if we want to call one of those two vectors, we are going to perform the call in this way a$a. So with first a, we are calling list a and then $ sign, and at the end, name of our vector that is contained within the list. If you want to call second element of b vector from list a, you are going to call it in this way a$b[2].

For video tutorial, check the link below



R Tutorial Playlist - Vector Basic Operations

 Not only that you can use vector element in your calculations, you can use entire vectors in order to get series of results.

a <- c(1, 2, 3)

b <- c(10, 20, 30)

Keep in mind that you need to have two vectors of equal number of element in order for this to work.

In case that you want to multiply those two, result is going to be another vector that is going to hold values that are result of multiplication of elements of those two vectors per index. So in case of our two vectors, result is going to be 10, 40, 90.

You could also perform calculations like this (a*b)[2] - 10. This is going to get us second element of first vector, multiplied by second element of second vector, and then from that number 10 is going to be subtracted.  So in our case, result is going to be 30.

Function paste is going to append string value to string element of a vector. So if you have vector like b <- c("a", "b") if you do something like a <- paste(b, "1" sep="_"), you are going to get result "a_1", "b_1". So function paste is going to add appending string to every element of vector a, and with optional argument sep, we are going to provide character that is going to separate appending and appended string.

You can also do some binary operations with function xor(a, TRUE) or a|b in case that our two arrays contain only bool values. 

For video on YouTube, check the link below.



R Tutorial Playlist - Vector

 Vector or collection in R is the basic type of array. It can hold any type of values except other vectors.

In order to create a vector type

a <- c(1, 2, 3, 4) or a <- c("1", "2", "3", "4") or a <- c(TRUE, TRUE, FALSE, TRUE)

So you see that in order to create vector, you have to use function c that stands for collection and elements in coma separated fashion.

Vector can't hold multiple types of values all at once. If you try to say something line a  <- c("1", 2, FALSE), you are going to end with a <- c("1", "2", "FALSE"), so in this case, all of values are going to be turned to strings.

If you try to add vector to a vector like in case a <- c(1, 2, 3, c(4, 5, 6)) you will end with single vector with elements 1, 2, 3, 4, 5, 6. So, if you try to add vector to a vector, elements of appending vector are going to be turned into elements of appended vector.

To append element to vector, use function append like b <- append(a, 36), and if you want to remove some element from vector use slicing:

  • b <- a[-5]  b is going to hold all of a elements except fifth.
  • b <- a[2:5] b is going to hold second, third, fourth, and fifth element of a.
  • b <- a[4] b is going to hold only fourth element of a. 
  • b <- a[3, 5] b is going to hold third and fifth element of a.
  • b <- a[-3, -5] b is going to hold all elements of a except third and fifth.
If you want to watch video tutorial about this subject, check the link below.



Wednesday, April 12, 2023

R Tutorial Playlist - Datetime

Functions Sys.Date() and Sys.time() are going to return present date and time respectively.

Function strntime("time, date or both" format="date format") is going to create date and time structure according to value and format you are providing.

Format in strntime function is going to be created based on keys in next list:

  • %Z for timezone
  • %z for offset from GMT
  • %Y for 4 digits year
  • %y for 2 digits year
  • %X for locale specific time
  • %x for locale specific date
  • %W for week of the year
  • %w for day of the week
  • %S for seconds
  • %p for AM/PM
  • %M for minute
  • %m for month
  • %j for day of the year
  • %I for hours in 12 hours format
  • %H for hours in 24 hours format
  • %d for date
So in next example a <- strntime("12.04.2023 22:24:36", format="%d.%m.%Y. %H:%M:%S"), after this functions is executed, variable a is going to hold value of "12.04.2023. 22:24:36". But variable a is not a string in this case. In order to print string out, you would have to call function format(a, "print me %H hours and %M minutes"). In this case, to we are going to get "print me 22 hours and 24 minutes" printed to our screen.

In order to use date and time object for calculations, we need to use additional package called lubridate.
Now we can simply use our date and time object like a<- a + hours(2) + minutes(18) in order to add additional 2 hours and 18 minutes to it.

For video tutorial, check the link below.



R Tutorial Playlist - How to use external scripts

 External script in R are considered to be other R script that you could use in your code. If you use function script("path to external script") you could use all of functions and variables which that script contains. With this single line of code, you are effectively importing all of code from external script to your code.

Check video tutorial below for this subject.



R Tutorial Playlist - How to load, install, uninstall, require, list packages

 Packages are libraries of R features. Some of them are core part of R, but most of them are not. Those non core packages could be imported into your code when necessary.

With command install.packages("package name") you are going to install single package to your system. You could also, instead of single package, provide collection of packages.

Command update.packages() is going to update all of packages already installed on your system.

Command library("package name") is going to import library to you R session. If instead of function library("package name"), you use command require("package name"), if there is no package with provided package name installed on your system, R is going to ask you to install required package, otherwise this function is going to return value FALSE.

Function installed.packages() is going to return entire list of installed packages.

Command uninstall.packages("package name") is going to remove package with provided package name. With this function, you could also instead of single package name, provide collection of package names.

Here is the link for YouTube video that deals with this subject.



Tuesday, April 11, 2023

R Tutorial Playlist - Function Sleep

 With function sleep you can pause your code execution. If you nest it in between other two commands, you are going to prolong time till all of that is done.

message("First command")

Sys.sleep(0.5)

message("Second message")

With this statement, we will have to wait 0.5 seconds before, our second message is printed. This function accepts only one argument and that is actual time expressed in seconds.

Check all of this on YouTube.



R Tutorial Playlist - Script Arguments

 In order to provide script arguments, first you would need to have an executable script. On Linux you can do that by providing the line 

#!/usr/bin/Rscript

When you change file itself to executable, this line is going to tell your OS that script should be executed by Rscript(R interpreter).

Now, in order to get script arguments, you should provide the next line.

args <- commandArgs(trailingOnly= TRUE)

args is variable that is going to store your arguments. Usually first argument in script is executable environment of that script; by providing trailingOnly set to TRUE, we are going to avoid turning path to our executable environment to our first argument. With this optional argument, your args is going to contain only values you have provided with script calling.

At the end, if you want to use your script arguments, just call variable args with index number of value you want to use like:

message(args[1])

If you want to see how all of this works, check video tutorial below.



R Tutorial Playlist - Text values and shell commands

 If you print some text to the screen with command print or just by typing it in your code, that text is going to be printed in raw form. So, even if you use escape character like in case of \", that is exactly what is going to be printed. Way to avoid that is to use message function like

message("\"some text to be printed\"")

in this case, instead of having result like:

\"some text to be printed\"

we are going to have

"some text to be printed"

so, function message is parsing input string and prints refined version to the screen.

And second part of this tutorial is dealing with shell commands. In order to send some command to the OS shell, you should use function system in a form:

system("command to be executed")

If you want to see video tutorial check the link below.



Monday, April 10, 2023

R Tutorial Playlist - Logical Operations

 Logical operations are those operations that as final result have one of two values; TRUE of FALSE.

Whenever you ask R something like

10>1

or

12<52

as result R is going to print FALSE as in the first case or TRUE as in the second case.

With command %in% you can ask whether some element is contained in an array like:

12 %in% c(3, 12, 26)

and in this case our result is going to be TRUE because 12 is contained in our array.

There are operators like ||- means 'or', and &&- means 'and' that allow you to combine conditions like:

12<10 || 15>5

12<10 && 15>5

In first case 'or' operator needs only one condition to be fulfilled in order for result to be TRUE, while in case of 'and' operator, you need to fulfill both conditions in order for result to be TRUE, what is not in our case.

And at the end, there is ! operator that simply means 'not'. If you put ! in front of any condition, result of that condition is going to be reversed.

!(1>10)

One is greater than ten but presence of operator 'not' in front, is going to reverse result from FALSE to TRUE.

Please check our YouTube video for more.



R Tutorial Playlist - Arithmetic Operations

 There is no programming language without this feature. R is different then other programming languages in regards of approach to this subject, because it treats most of values in table form out of box. This is what usually confuses new R developers, especially if they have learned some other programming language previously.

First, we are going to talk about 4 basic arithmetic operations:

Let's have two variables

a<-21

b<-10

In  order to sum those values c <- a + b or sum(a, b)

To subtract one from the another c <- a - b

To multiply one with the another c <- a * b

To divide one from the another but to keep decimal part c <- a / b

To divide but to get round integer c <- ceiling(a,b) and c <- a%\%b

To get modulo number from division c <- a%%b

To calculate exponent c <-  a ^ b

And finally some trigonometric functions sin(a), cos(a), tan(e), log(a)


If you prefer video tutorial, please check this one on YouTube



Saturday, April 8, 2023

R Tutorial Playlist - Basic Types

 Keep in mind that R treats all of values as arrays or even as tables of values, out of the box. Types of values, we are dealing with in R are characters, logical and numeric.

R is not strict with variable types.

a= 10

a="ho ho" or 

a= False

all of those examples are totally fine. Plus there is one more way more preferable to R coders to assign value to a variable:

a <- "some value"

You could do something like

"some value"->b

but previous example is preferable

In this video we are also talking about function invisible that is going to prevent printing of variable value to the screen.

With function typeof you can print type of a variable.

If you want to see, how all of this works in real example, check this video on our YouTube channel.