R Language Basics and R FAQs

The post is about R Language Basics and R Language Frequently Asked Questions. The contents are in the form of questions and answers. Let us start with R Language Basics Questions and Answers.

R Basics

Question: How to start (Run) R Language in the Windows Operating System?
Answer: In Microsoft Windows, during installation, the R installer will have created a Start menu item and an icon for R on your system’s desktop. Double-click the R icon from the desktop or the start menu list to Run the R program.

For Windows 7, 8, or 10, you can use a search term like “R x64 3.2.1” (64-bit version) or “R i386 3.2.1” (32-bit version). R GUI will launch.

Question: How R can be used as a calculator?
Answer: Starting R will open the console where the user can type commands. To use R as a calculator one has to enter the arithmetical expression after > prompt. For example

> 5 + 4
> sqrt(37)
> 2*4^2+17*4-3

Question: What is a workspace in R?
Answer: The workspace in R is an image that contains a record of the computations one has done and it may contain some saved results.

Question: How to record works[ace in R?
Answer: Rather than saving the workspace, one can record all the commands that one has entered in the R console. Recording work in R, the R workspace can be reproduced. The easiest way is to enter the commands in R’s script editor available in the File menu of R GUI.

Question: What is R Script Editor?
Answer: The r script editor is a place where one can enter commands. Commands can be executed by highlighting them and hitting CTRL+R (mean RUN). At the end of an R session, one can save the final script for a permanent record of one’s work.

A text editor such as Notepad can also be used for this purpose.
Note that in the R console, only one command can be entered at a time because after pressing the Enter key the R command executed immediately.

Question: How to Quit the R session?
Answer: In the R console on the R command prompt just type

> q( )
rfaqs.com r Language Basics and R Faqs

Question: What is q()?
Answer: The q() is a function that is used to tell R to quit. When q() is entered in the R console and press the Enter key, you will be asked whether to save an image of the current workspace or not or to cancel. Note that only typing q tells R to show the content of this function. The action of this function is to quit R.

MCQs Statistics with Answers

Reading Creating and Import Data in R

There are many ways to read data into R-Language.  We will learn here how to import data in R Language too. We can also generate certain kinds of patterned data. Some of them are

Reading Data from the Keyboard Directly

For small data (few observations) one can input data in vector form directly on R Console, such as

x <- c(1,2,3,4,5)
y <-c('a', 'b', 'c')

In vector form, data can be on several lines by omitting the right parentheses, until the data are complete, such as

x <-c(1,2 
      3,4)

Note that it is more convenient to use the scan function, which permits the index of the next entry.

Using Scan Function

For small data sets it is better to read data from the console by using the scan function. The data can be entered on a separate line, by using a single space and/or tab. After entering the complete required data, pressing twice the enter key will terminate the scanning.

X <-scan()
     3 4 5
     4 5 6 7
     2 3 4 5 6 6

Reading String Data using the “what” Option

y <- scan(what=" ")
      red green blue
      white

The scan function can be used to import data. The scan function returns a list or a vector while read.table function returns a data frame. It means that the scan function is less useful for imputing “rectangular” type data.

Reading data from ASCII or plain text files into R as Data Frame

The read.table function reads any type of delimited ASCII file. It can be numeric and character values. Reading data into R by read.table is the easiest and most reliable method. The default delimiter is a blank space.

data <-read.table(file=file.choose()) #select from dialog box
data <-read.table("http://itfeature.com/test.txt", header=TRUE)) # read from web site

Note that read.table command can also be used for reading data from the computer disk by providing an appropriate path in inverted commas such as

data <-read.table("D:/data.txt", header=TRUE)) # read from your computer

For missing data, read.table will not work and you will receive an error. For missing values the easiest way to fix this error, change the type of delimiter by using a sep argument to specify the delimiter.

data <-read.table("http//itfeature.com/missing_comma.txt", header=TRUE, sep=","))

Comma-delimited files can be read in by read.table function and sep argument, but it can also be read in by the read.csv function specifically written for comma-delimited files. To display the contents of the file use print() function or file name.

data <-read.csv(file=file.choose())

Reading in fixed formatted files

To read data in fixed format use read.fwf function and argument width are used to indicate the width (number of columns) for each variable. In this format variable names are not there in the first line, therefore they must be added after reading the data. Variable names are added by dimnames function and the bracket notation to indicate that we are attaching names to the variables (columns) of the data file. Anyhow there are several different ways to do this task.

data <-read.fwf("http://itfeature.com/test_fixed.txt", width=c(8,1,3,1,1,1))
dimnames(data)[[2]]
c("v1", "v2", "v3", "v4", "v5","v6")

Import Data In R

Importing data in R is fairly simple. For Stata and Systat, use the foreign package. For SPSS and SAS recommended package is the Hmisc package for ease and functionality. See the Quick-R section on packages, for information on obtaining and installing these packages. Examples of importing data in R are provided below.

From Excel

On Windows systems, you can use the RODBC package to access Excel files. The first row of the Excel file should contain variable/column names.

# Excel file name is myexcel and WorkSheet name is mysheet
library(RODBC)
channel <- odbcConnectExcel("c:/myexel.xls")
mydata <- sqlFetch(channel, "mysheet") 
odbcClose(channel)
From SPSS
# First save SPSS dataset in trasport format
get file='c:\data.sav'
export outfile='c:\data.por' 
library(Hmisc)
mydata <- spss.get("c:/data.por", use.value.labels=TRUE)   # "use.value.labels" option converts value labels to R factors.
From SAS
# save SAS dataset in trasport format
libname out xport 'c:/mydata.xpt';
data out.data;
set sasuser.data;
run;

# in R
library(Hmisc)
mydata <- sasxport.get("c:/data.xpt")
# character variables are converted to R factors

From Stata
# input Stata file
library(foreign)
mydata <- read.dta("c:/data.dta")

From systat
# input Systat file
library(foreign)
mydata <- read.systat("c:/mydata.dta")
Importing Data in R

Accessing Data in R Library

Many of the R libraries including CAR library contain data sets. For example to access the Duncan data frame from the CAR library in R type the following command on R Console

library(car)
data(Duncan)
attach(Duncan)

Some Important Commands for Dataframes

data        #displays the entire data set on command editor
head(data)  #displays the first 6 rows of dataframe
tail(data)  #displays the last 6 rows of dataframe
str(data)   #displays the names of variable and their types
names(data) #shows the variable names only
rename(V1,Variable1, dataFrame=data) # renames V1 to variable 1; note that epicalc packagemust be installed
ls()        #shows a list of objects that are available
attach(data)#attached the dataframe to the R search path, which makes it easy to access variables names.

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 the 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 to browse 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 a 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. The 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)

Getting Help About 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 a built-in help facility which is similar to man facility in Unix. For beginners to get help, the help() function or a symbol ? (question mark only) can be used to get help with different commands of the R language.

Questions: Provide some examples of getting help about different functions used in 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 with 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 about different functions and object in 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 about R Language

x  Powerful Protection for WordPress, from Shield Security
This Site Is Protected By
Shield Security