R Basics

FAQ about R basic

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 

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

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))
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
channel <- odbcConnectExcel("c:/myexel.xls")
mydata <- sqlFetch(channel, "mysheet") 
# First save SPSS dataset in trasport format
get file='c:\data.sav'
export outfile='c:\data.por' 
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;

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

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

From systat
# input Systat file
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


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

Save and Load RData Workspace

In this post, we will learn about Save and Load RData Workspace

Question: Can I save my work in R Language?
Answer: R language facilitates saving one’s R work.

Question: How to save work done in R?
Answer: All of the objects and functions that are created (your 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 an alternative to save workspace in R?
Answer: Yes! You can also save the workspace using the file menu. For this, click the 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 the workspace in R?
Answer: The .RData files can be accessed through the file menu. To access the 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.

Save and Load RData Workspace

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 the 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 a different path.

> history("d:/filename.Rhistory")

Question: Can commands in the R session be saved through the File menu?
Answer: Yes command in the R session be saved through the 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.

Online MCQs Test preparation website with Answers

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