Category: R FAQS

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

How to View Source Code of R Method/ Function?

Source Code of R Method

There are different ways to view the source code of an R method or function. It will help to know how function is working.

Internal Functions
If you want to see the source code of internal function (functions from base packages), just type the name of the function at R prompt such as;

> rowMeans
view R code of method

Functions or Methods from S3 Class System
For S3 classes, methods function can be used to list the methods for a particular generic function or class.

> methods(predict)

view R code S3 Class
Note that “Non-Visible functions are asterisked” means that the function is not exported from its package’s namespace.

One can still view its source code via the ::: function such as

> stats:::predict.lm

or by using getAnywhere() function, such as

> getAnywhere(predict.lm)

Note that the getAnywhere() function is useful as you don’t need to know from which package the function or method is came from.

Functions or Methods from S4 Class System
The S4 system is a newer method dispatch system and is an alternative to the S3 system. The package ‘Matrix’ is an example of S4 function.

> library(Matrix)
> chol2inv
view R code S4 Class
The output already offers a lot of information. The standardGeneric is an indicator of an S4 function. The method to see defined S4 methods is to use showMethods(chol2inv), that is;

>showMethods(chol2inv)
view R code S4 System
The getMethod can be used to see the source code of one of the methods, such as,
> getMethod (“chol2inv”, “diagonalMatrix”)
view R code S4 System
Functions that Calls Unexported Functions
In the case of unexported functions such as ts.union, .cbindts and .makeNamesTs from the stats namespace, one can view source code of these unexported functions using ::: operator or getAnywhere() function, for example;
> stats::: .makeNamesTs
> getAnywhere(.makeNamesTs)
view R code S4 System
View on Youtube

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