Lists

1. Tutorial

Lists are the R objects which contain elements of different types like − numbers, strings, vectors and another list inside it. A list can also contain a matrix or a function as its elements. List is created using list() function. Creating a List Following is an example to create a list containing strings, numbers, vectors and a logical values. When we execute the above code, it produces the following result − Naming List Elements The list elements can be given names and they can be accessed using these names. When we execute the above code, it produces the following result − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Accessing List Elements Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names. We continue to use the list in the above example − When we execute the above code, it produces the following result − Manipulating List Elements We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list. But we can update any element. When we execute the above code, it produces the following result − Merging Lists You can merge many lists into one list by placing all the lists inside one list() function. When we execute the above code, it produces the following result − Converting List to Vector A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this conversion, we use the unlist() function. It takes the list as input and produces a vector. When we execute the above code, it produces the following result −

October 29, 2024 / 0 Comments
read more

Strings

1. Tutorial

Any value written within a pair of single quote or double quotes in R is treated as a string. Internally R stores every string within double quotes, even when you create them with single quote. Rules Applied in String Construction Examples of Valid Strings Following examples clarify the rules about creating a string in R. When the above code is run we get the following output − Examples of Invalid Strings When we run the script it fails giving below results. String Manipulation Concatenating Strings – paste() function Many strings in R are combined using the paste() function. It can take any number of arguments to be combined together. Syntax The basic syntax for paste function is − Following is the description of the parameters used − Example When we execute the above code, it produces the following result − Formatting numbers & strings – format() function Numbers and strings can be formatted to a specific style using format() function. Syntax The basic syntax for format function is − Following is the description of the parameters used − Example When we execute the above code, it produces the following result − Counting number of characters in a string – nchar() function This function counts the number of characters including spaces in a string. Syntax The basic syntax for nchar() function is − Following is the description of the parameters used − Example When we execute the above code, it produces the following result − Changing the case – toupper() & tolower() functions These functions change the case of characters of a string. Syntax The basic syntax for toupper() & tolower() function is − Following is the description of the parameters used − Example When we execute the above code, it produces the following result − Extracting parts of a string – substring() function This function extracts parts of a String. Syntax The basic syntax for substring() function is − Following is the description of the parameters used − Example When we execute the above code, it produces the following result −

October 29, 2024 / 0 Comments
read more

Functions

1. Tutorial

A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions. In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions. The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects. Function Definition An R function is created by using the keyword function. The basic syntax of an R function definition is as follows − Function Components The different parts of a function are − R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Built-in Function Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(…) etc. They are directly called by user written programs. You can refer most widely used R functions. When we execute the above code, it produces the following result − User-defined Function We can create user-defined functions in R. They are specific to what a user wants and once created they can be used like the built-in functions. Below is an example of how a function is created and used. Calling a Function When we execute the above code, it produces the following result − Calling a Function without an Argument When we execute the above code, it produces the following result − Calling a Function with Argument Values (by position and by name) The arguments to a function call can be supplied in the same sequence as defined in the function or they can be supplied in a different sequence but assigned to the names of the arguments. When we execute the above code, it produces the following result − Calling a Function with Default Argument We can define the value of the arguments in the function definition and call the function without supplying any argument to get the default result. But we can also call such functions by supplying new values of the argument and get non default result. When we execute the above code, it produces the following result − Lazy Evaluation of Function Arguments to functions are evaluated lazily, which means so they are evaluated only when needed by the function body. When we execute the above code, it produces the following result −

October 29, 2024 / 0 Comments
read more

Decision making

1. Tutorial

Decision making structures require the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − R provides the following types of decision making statements. Click the following links to check their detail. Sr.No. Statement & Description 1 if statementAn if statement consists of a Boolean expression followed by one or more statements. 2 if…else statementAn if statement can be followed by an optional else statement, which executes when the Boolean expression is false. 3 switch statementA switch statement allows a variable to be tested for equality against a list of values.

October 29, 2024 / 0 Comments
read more

Operators

1. Tutorial

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides following types of operators. Types of Operators We have the following types of operators in R programming − Arithmetic Operators Following table shows the arithmetic operators supported by R language. The operators act on each element of the vector. Operator Description Example + Adds two vectors v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v+t)it produces the following result −[1] 10.0 8.5 10.0 − Subtracts second vector from the first v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v-t)it produces the following result −[1] -6.0 2.5 2.0 * Multiplies both vectors v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v*t)it produces the following result −[1] 16.0 16.5 24.0 / Divide the first vector with the second v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v/t)When we execute the above code, it produces the following result −[1] 0.250000 1.833333 1.500000 %% Give the remainder of the first vector with the second v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v%%t)it produces the following result −[1] 2.0 2.5 2.0 %/% The result of division of first vector with second (quotient) v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v%/%t)it produces the following result −[1] 0 1 1 ^ The first vector raised to the exponent of second vector v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v^t)it produces the following result −[1] 256.000 166.375 1296.000 Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Relational Operators Following table shows the relational operators supported by R language. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value. Operator Description Example > Checks if each element of the first vector is greater than the corresponding element of the second vector. v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v>t)it produces the following result −[1] FALSE TRUE FALSE FALSE < Checks if each element of the first vector is less than the corresponding element of the second vector. v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v < t)it produces the following result −[1] TRUE FALSE TRUE FALSE == Checks if each element of the first vector is equal to the corresponding element of the second vector. v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v == t)it produces the following result −[1] FALSE FALSE FALSE TRUE <= Checks if each element of the first vector is less than or equal to the corresponding element of the second vector. v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v<=t)it produces the following result −[1] TRUE FALSE TRUE TRUE >= Checks if each element of the first vector is greater than or equal to the corresponding element of the second vector. Live Demov <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v>=t)it produces the following result −[1] FALSE TRUE FALSE TRUE != Checks if each element of the first vector is unequal to the corresponding element of the second vector. v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v!=t)it produces the following result −[1] TRUE TRUE TRUE FALSE Logical Operators Following table shows the logical operators supported by R language. It is applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value TRUE. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value. Operator Description Example & It is called Element-wise Logical AND operator. It combines each element of the first vector with the corresponding element of the second vector and gives a output TRUE if both the elements are TRUE. v <- c(3,1,TRUE,2+3i) t <- c(4,1,FALSE,2+3i) print(v&t)it produces the following result −[1] TRUE TRUE FALSE TRUE | It is called Element-wise Logical OR operator. It combines each element of the first vector with the corresponding element of the second vector and gives a output TRUE if one the elements is TRUE. v <- c(3,0,TRUE,2+2i) t <- c(4,0,FALSE,2+3i) print(v|t)it produces the following result −[1] TRUE FALSE TRUE TRUE ! It is called Logical NOT operator. Takes each element of the vector and gives the opposite logical value. v <- c(3,0,TRUE,2+2i) print(!v)it produces the following result −[1] FALSE TRUE FALSE FALSE The logical operator && and || considers only the first element of the vectors and give a vector of single element as output. Operator Description Example && Called Logical AND operator. Takes first element of both the vectors and gives the TRUE only if both are TRUE. v <- c(3,0,TRUE,2+2i) t <- c(1,3,TRUE,2+3i) print(v&&t)it produces the following result −[1] TRUE || Called Logical OR operator. Takes first element of both the vectors and gives the TRUE if one of them is TRUE. v <- c(0,0,TRUE,2+2i) t <- c(0,3,TRUE,2+3i) print(v||t)it produces the following result −[1] FALSE Assignment Operators These operators are used to assign values to vectors. Operator Description Example <−or=or<<− Called Left Assignment v1 <- c(3,1,TRUE,2+3i) v2 <<- c(3,1,TRUE,2+3i) v3 = c(3,1,TRUE,2+3i) print(v1) print(v2) print(v3)it produces the following result −[1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i ->or->> Called Right Assignment c(3,1,TRUE,2+3i) -> v1 c(3,1,TRUE,2+3i) ->> v2 print(v1) print(v2)it produces the following result −[1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i Miscellaneous Operators These operators are used to for specific purpose and not general mathematical or logical computation. Operator Description Example : Colon operator. It creates the series of numbers in sequence for a vector. v <- 2:8 print(v) it produces the following result −[1] 2 3 4 5 6 7 8 %in% This operator is used to identify if an element belongs to a vector. v1 <- 8 v2 <- 12 t <- 1:10 print(v1 %in% t) print(v2 %in% t) it produces the following result −[1] TRUE [1] FALSE %*% This operator is used to multiply a

October 29, 2024 / 0 Comments
read more

Variables

1. Tutorial

A variable provides us with named storage that our programs can manipulate. A variable in R can store an atomic vector, group of atomic vectors or a combination of many Robjects. A valid variable name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter or the dot not followed by a number. Variable Name Validity Reason var_name2. valid Has letters, numbers, dot and underscore var_name% Invalid Has the character ‘%’. Only dot(.) and underscore allowed. 2var_name invalid Starts with a number .var_name,var.name valid Can start with a dot(.) but the dot(.)should not be followed by a number. .2var_name invalid The starting dot is followed by a number making it invalid. _var_name invalid Starts with _ which is not valid Variable Assignment The variables can be assigned values using leftward, rightward and equal to operator. The values of the variables can be printed using print() or cat() function. The cat() function combines multiple items into a continuous print output. When we execute the above code, it produces the following result − Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical class is coerced to numeric class making TRUE as 1. Data Type of a Variable In R, a variable itself is not declared of any data type, rather it gets the data type of the R – object assigned to it. So R is called a dynamically typed language, which means that we can change a variable’s data type of the same variable again and again when using it in a program. When we execute the above code, it produces the following result − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Finding Variables To know all the variables currently available in the workspace we use the ls() function. Also the ls() function can use patterns to match the variable names. When we execute the above code, it produces the following result − Note − It is a sample output depending on what variables are declared in your environment. The ls() function can use patterns to match the variable names. When we execute the above code, it produces the following result − The variables starting with dot(.) are hidden, they can be listed using “all.names = TRUE” argument to ls() function. When we execute the above code, it produces the following result − Deleting Variables Variables can be deleted by using the rm() function. Below we delete the variable var.3. On printing the value of the variable error is thrown. When we execute the above code, it produces the following result − All the variables can be deleted by using the rm() and ls() function together. When we execute the above code, it produces the following result −

October 29, 2024 / 0 Comments
read more

Data Types

1. Tutorial

Generally, while doing programming in any programming language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that, when you create a variable you reserve some space in memory. You may like to store information of various data types like character, wide character, integer, floating point, double floating point, Boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. In contrast to other programming languages like C and java in R, the variables are not declared as some data type. The variables are assigned with R-Objects and the data type of the R-object becomes the data type of the variable. There are many types of R-objects. The frequently used ones are − The simplest of these objects is the vector object and there are six data types of these atomic vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic vectors. Data Type Example Verify Logical TRUE, FALSE v <- TRUE print(class(v))it produces the following result −[1] “logical” Numeric 12.3, 5, 999 v <- 23.5 print(class(v))it produces the following result −[1] “numeric” Integer 2L, 34L, 0L v <- 2L print(class(v))it produces the following result −[1] “integer” Complex 3 + 2i v <- 2+5i print(class(v))it produces the following result −[1] “complex” Character ‘a’ , ‘”good”, “TRUE”, ‘23.4’ v <- “TRUE” print(class(v))it produces the following result −[1] “character” Raw “Hello” is stored as 48 65 6c 6c 6f v <- charToRaw(“Hello”) print(class(v))it produces the following result −[1] “raw” In R programming, the very basic data types are the R-objects called vectors which hold elements of different classes as shown above. Please note in R the number of classes is not confined to only the above six types. For example, we can use many atomic vectors and create an array whose class will become array. Vectors When you want to create vector with more than one element, you should use c() function which means to combine the elements into a vector. Live Demo When we execute the above code, it produces the following result − Lists A list is an R-object which can contain many different types of elements inside it like vectors, functions and even another list inside it. When we execute the above code, it produces the following result − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Matrices A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the matrix function. When we execute the above code, it produces the following result − Arrays While matrices are confined to two dimensions, arrays can be of any number of dimensions. The array function takes a dim attribute which creates the required number of dimension. In the below example we create an array with two elements which are 3×3 matrices each. When we execute the above code, it produces the following result − Factors Factors are the r-objects which are created using a vector. It stores the vector along with the distinct values of the elements in the vector as labels. The labels are always character irrespective of whether it is numeric or character or Boolean etc. in the input vector. They are useful in statistical modeling. Factors are created using the factor() function. The nlevels functions gives the count of levels. When we execute the above code, it produces the following result − Data Frames Data frames are tabular data objects. Unlike a matrix in data frame each column can contain different modes of data. The first column can be numeric while the second column can be character and third column can be logical. It is a list of vectors of equal length. Data Frames are created using the data.frame() function. When we execute the above code, it produces the following result −

October 29, 2024 / 0 Comments
read more

Basic Syntax

1. Tutorial

As a convention, we will start learning R programming by writing a “Hello, World!” program. Depending on the needs, you can program either at R command prompt or you can use an R script file to write your program. Let’s check both one by one. R Command Prompt Once you have R environment setup, then it’s easy to start your R command prompt by just typing the following command at your command prompt − This will launch R interpreter and you will get a prompt > where you can start typing your program as follows − Here first statement defines a string variable myString, where we assign a string “Hello, World!” and then next statement print() is being used to print the value stored in variable myString. R Script File Usually, you will do your programming by writing your programs in script files and then you execute those scripts at your command prompt with the help of R interpreter called Rscript. So let’s start with writing following code in a text file called test.R as under − Save the above code in a file test.R and execute it at Linux command prompt as given below. Even if you are using Windows or other system, syntax will remain same. When we run the above program, it produces the following result. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Comments Comments are like helping text in your R program and they are ignored by the interpreter while executing your actual program. Single comment is written using # in the beginning of the statement as follows − R does not support multi-line comments but you can perform a trick which is something as follows − Though above comments will be executed by R interpreter, they will not interfere with your actual program. You should put such comments inside, either single or double quote.

October 29, 2024 / 0 Comments
read more

Environment Setup

1. Tutorial

Local Environment Setup If you are still willing to set up your environment for R, you can follow the steps given below. Windows Installation You can download the Windows installer version of R from R-3.2.2 for Windows (32/64 bit) and save it in a local directory. As it is a Windows installer (.exe) with a name “R-version-win.exe”. You can just double click and run the installer accepting the default settings. If your Windows is 32-bit version, it installs the 32-bit version. But if your windows is 64-bit, then it installs both the 32-bit and 64-bit versions. After installation you can locate the icon to run the Program in a directory structure “R\R3.2.2\bin\i386\Rgui.exe” under the Windows Program Files. Clicking this icon brings up the R-GUI which is the R console to do R Programming. Linux Installation R is available as a binary for many versions of Linux at the location R Binaries. The instruction to install Linux varies from flavor to flavor. These steps are mentioned under each type of Linux version in the mentioned link. However, if you are in a hurry, then you can use yum command to install R as follows − Above command will install core functionality of R programming along with standard packages, still you need additional package, then you can launch R prompt as follows − Now you can use install command at R prompt to install the required package. For example, the following command will install plotrix package which is required for 3D charts.

October 29, 2024 / 0 Comments
read more

Overview

1. Tutorial

R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team. The core of R is an interpreted computer language which allows branching and looping as well as modular programming using functions. R allows integration with the procedures written in the C, C++, .Net, Python or FORTRAN languages for efficiency. R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems like Linux, Windows and Mac. R is free software distributed under a GNU-style copy left, and an official part of the GNU project called GNU S. Evolution of R R was initially written by Ross Ihaka and Robert Gentleman at the Department of Statistics of the University of Auckland in Auckland, New Zealand. R made its first appearance in 1993. Features of R As stated earlier, R is a programming language and software environment for statistical analysis, graphics representation and reporting. The following are the important features of R − As a conclusion, R is world’s most widely used statistics programming language. It’s the # 1 choice of data scientists and supported by a vibrant and talented community of contributors. R is taught in universities and deployed in mission critical business applications. This tutorial will teach you R programming along with suitable examples in simple and easy steps.

October 29, 2024 / 0 Comments
read more

Posts pagination

Previous 1 … 86 87 88 … 445 Next