Category: R Basics

Vectors in R Language

In R Language, a vector is the simplest data structure. A vector in R is also an object that contains elements having the same data type. To create a vector (say ‘x’) of the same type (say double) of elements consisting of five elements one can use c() function. For example,

Creating a vector in R using c() function

> x <- c(10, 7, 3, 2, 1)

The c() function can be used to combine a different number of vectors into a single vector. A single number is regarded as a vector of length one. For example, a vector (say ‘y’) is created by combing the existing vector(s) with a single number.

Appending a number to existing vector(s)

One can append a number to existing vector or even append a vector with another vector. For example,

> y <- c(x, .55)
> z <- c(x, y)

Extracting vector element(s)

The simplest example to select a particular element of a vector can be performed by using a subscription mechanism. That is, use the name of the vector with square ([ ]) bracket with a number in it indicating the position of a vector element. For example,

> x[1]     # shows first element of vector  ‘x’
> x[1:2] # shows first two elements of vector ‘x’
> x[3:5] # shows elements of vector ‘x’ from index 3 to 5

Note that a positive number is used as a subscript index in square bracket. A positive subscript indicates the index (position) of a number to extract from the vector. A negative number as the index can also be used, which is used to select all the elements except the number(s) that are used in the square bracket ([ ]).

The example of negative index is;

> x[-1]   # shows all elements of vector ‘x’ except first element
> x[-(1:2)] # shows elements of vector ‘x’ except first two elements

Also note that if subscripting number exceeds the number of elements in a vector, then it will result in NA (not available). For example,

> x[7]
> x[1:10]

Updating vector elements

One or more elements of a vector can be changed by the subscripting mechanism. For example, to change the 4th element of a vector, one can proceed as follow;

> x[4] <- 15   # 4th position of vector ‘x’ is updated to 15
> x[1:3] < – 4 # first three numbers are updated to 4
> x[1:3] <- c(1,2,3) # first three numbers are updated to 1, 2, and 3

R workspace, object and .RData file

The R program’s structure is similar to the programs written in other computer languages such as C or its successors C++ and Java. However, important differences between these languages and R are (i) R has no header files, (ii) most of the declarations are implicit, (iii) there are no pointers in R, and (iv) text and strings as vectors can be defined and manipulated directly.

R is a functional language. Most of the computation in R is handled using functions. The R language environment is designed to facilitate the development of new scientific computation tools.

Every thing (such as functions and data structure) in R is an object. Too see the names of all objects in R workspace, on R command prompt just type,

>ls()

objects() is an alternative to ls() function. Similarly, typing the name of any object on R prompt displays (prints) the content of that object. As an example type q, mean, and lm etc. on R prompt.

It is possible to save individual object or collection of objects into a named image file. The named image file have extension of .RData. Som e possibilities to save object from R workspace are:

To save content of R workspace into a file .RData, type

> save.image()

To save objects in file archive.RData, type

> save.image(file = “archive.RData”)

To save some required objects in data.RData, type

> save(x, y, file = “data.RData”)

These image files can be attached to make objects available in the next R session. For example.

> attached (“arvhive.RData”)

R workspace

Note that when quitting, R offers the option of saving workspace image. By default workspace is saved in an image file (.RData) in working directory. The image file can e used in the next R session. Saving the workspace image will save everything from current workspace. Therefore, use rm() function to remove objects that are not further required in next R session.

For further details about saving and loading R workspace visit: http://rfaqs.com/saving-and-loading-r-workspace

R Basics

Question 1: How can I retrieve (load) the work that is saved using history function in R?
Answer: The loadhistory() function will load an “.Rhistory“file.

> loadhistory(“d:/file_name.Rhistory”)

This function will load file named “file_name.Rhistory” from D: drive.

The other way may be to access .Rhistory file through the file menu. For this click File and then Load history. From the dialog box appeared  browse to the folder where you saved the .Rhistory file and click open to start working.

Question 2: How do I use a script of commands and functions saved in a text file?
Answer: The script of commands and functions saved in a text file (also called script file) can be used by writing the following command.

> source(“d:/file_name.txt”)

The “file_name.txt” will load from D: drive.

Question 3: How do I get R to echo back the R commands and functions in a script file that I am sourcing into R? That is, the functions that I have written, I want to see these functions are being executed.
Answer: use echo=TRUE argument by using source() function

source(“d:/file_name.txt”, echo=T)

Question 4: How do I close the help file when working on a Macintosh operating system?
Answer: Typing just q will close the help file and bring you back to the R console.

Question 5: How can I see a list of currently available objects in R?
Answer: Use the objects() or ls() functions to see the list of objects currently available

objects()
> ls()

Question 6: How do I remove/delete unwanted objects and functions?
Answer: The rm() function can be used to delete or remove the objects that are not required. Commands  below will delete objects named object_name1 & object_name2 and functions named function_name1 & function_name2.

> rm(object_name1, object_names2)
> rm(function_name1, function_name2)

R FAQs: Getting Help with R

Question: How one can get help about different command in R Language?
Answer: There are many ways to get help about the different command (functions). R has built-in help facility which is similar to man facility in Unix. For beginners to get help with R language, help() function or ? can be used to get help about different commands of R language.

Questions: Provide some examples of getting help with R?
Answer: To get more information on any specific R command (function), for example for getting help about solve(), lm(), plot() etc, write the following commands at R prompt:

> help(solve)
> help(lm)
> help(plot)

Question: Can one get help for special symbols, characters in R Language?
Answer: Yes one can get help for special characters. For example;

> help(“[[“)
> help(“[“)
> help(“^”)
> help(“$”)
> help(“%%”)

Question: What help.start() does?
Answer: The help.start() will launch a web browser that allows the help pages to browsed with hyperlinks. It can be a better way to get help about different functions.

Question: There is help.search() command. What for the purpose it is?
Answer: The help.search() command allows searching for help in various ways. To get what help.search() functions do, write this command at R prompt;

> help(help.search)

Question: Provide some details about help.search() function and also illustrate it by providing some examples?
Answer: The help.search() allows for searching the help system for documentation matching a given character string in the (file) name, alias, title, concept or keyword entries (or any combination thereof), using either fuzzy matching or regular expression matching. Names and titles of the matched help entries are displayed nicely formatted. The examples are:

> help.search(“linear”)
> help.search(“linear models”)
> help.search(“print”)
> help.search(“cat”)

Question: How ? can be used to get help with R language?
Answer: The ? mark can be used to get help with Windows version of R Language. For example;

> ?print
> ?help
> ?”[[“
> ?methods
> ?lm

For further detials, follow the link Getting Help with R Language

R FAQs: Saving and Loading R workspace

Question: Can I save my work in R Language?
Answer: R language facilitates to save ones R work.

Question: How to save work done in R?
Answer: All of the objects and functions that are created (you R workspace) can be saved in a file .RData by using the save() function or the save.image() function. It is important that when saving R work in a file, remember to include the .RData extension.

> save(file=”d:/filename.RData”)
> save.image(“d:/filename.RData”)

Question: Is there alternative to save workspace in R?
Answer: Yes! You can also save work space using file menu. For this, click File menu and then click save workspace. You will see the dialog box, browse to the folder where you want to save the file and provide the file name of your own choice.

Question: How one can access the saved work, while work is saved using save.image() function?
Answer: The load() function can be used to load a .RData file.

> load (“d:/filename.RData”)

Question: Is there any other alternative to load workspace in R?
Answer: The .RData files can be accessed through the file menu. To access file click File and then load workspace. A dialog box will appear, browse to the folder where you saved the .RData file and click open.

Question: How do one can save all the commands that are used in an R session?
Answer: Saving R commands used in an R session means you want to save history of your R session in an .Rhistory file by using the history() function. It is important to include the .Rhistory extension when saving the file at different path.

> history(“d:/filename.Rhistory”)

Question: Can commands in R session be saved through File menu?
Answer: Yes command in R session be saved through file menu. For this click File and then save history. A dialog box will appear, browse to the folder where you want to save the file (that will contain R commands in a session) and provide the file name of your own choice.