R Basic Functions

2016/01/03

To start coding with R you need to know few basic commands.

getwd()     # print the Current Working Directory - cwd
ls()          # list the objects in the current workspace
setwd("./") # set working directory to "./" 

# View and set options for the session:
help(options)         # learn about available options
options()               # view current option settings
options(digits=3)   # example: number of digits to print output

# Work with your previous commands
history()                     # display last 25 commands
history(max.show=Inf)   # display ALL previous commands

# Save your command history
savehistory(file="myfile")  # default is ".Rhistory"

# Recall your command history
loadhistory(file="myfile")  # default is ".Rhistory"

# Save the workspace to the file .Rdata in the cwd
save.image()

# Save/load specific objects to a file
# if you don't specify the path, the cwd is assumed
save(myfilename,file="myfile.RData")
load(myfilename,file="myfile.RData")

q() # quit R. You will be prompted to save the workspace.

More useful functions

lenght()    # number of elements or components
str()       # structure of an object
class()     # class or type of an object
names()     # names

c(object,object,...)       # combine objects into a vector
cbind(object, object, ...) # combine objects as columns
rbind(object, object, ...) # combine objects as rows 

object     # prints the object

ls()       # list current objects
rm(object) # delete an object

newobject <- edit(object) # edit copy and save as newobject 
fix(object)               # edit in place

Folders and files

In R you can create folders and text files by simple commands.

# Create new TempFolder
dir.create("TempFolder")

# Create an empty text file in TempFolder
file.create("./TempFolder/tekstitiedosto.txt")

# Create text file and write few lines of text there 
fileConn <- file("./TempFolder/tekstitiedosto.txt")
writeLines(c("Hello", "World"), fileConn)
close(fileConn)

Zipping

zipnimi <- "rcodes.zip"   # new zip file name
# Zip files
filut <- list.files("./MyCodes/", recursive=TRUE)
zip(zipnimi, files=paste(d, files, sep="/"))

# Unzip
unzip(zipnimi, exdir = "./temp")

File copy

# copy the files to the new folder
file.copy(from=filestocopy, to=targetdir, recursive = FALSE, copy.mode = TRUE)

Packages and libraries

.libPaths() # get library location
library()   # see all packages installed
search()    # see packages currently loaded