Blog

This article provides a summary of 'Most Useful' & 'Frequently Used' R / R-Studio commands with Example.

Note 1 - all the mentioned commands / features are tested on following R Version / Release 

language R 
version.string R version 3.5.1 (2018-07-02)

Note 2 - Also please note that R is Case Sensitive ( meaning we have to be careful with Upper & Lower Casing of our R Commands / Instructions )

1) [R] Get all the details of the version of the R running in your R Environment  :  version 

Example Code executed in R-Studio -
> version
                                          
platform        x86_64-w64-mingw32          
arch            x86_64                      
os              mingw32                     
system          x86_64, mingw32             
status                                     
major          3                           
minor          5.1                         
year            2018                        
month          07                          
day            02                          
svn rev        74947                       
language        R                           
version.string R version 3.5.1 (2018-07-02)
nickname        Feather Spray    


2) [R] Find the specific version number only info of the R running in your R Environment  :  R.version.string

Example Code executed in R-Studio -
> R.version.string
[1] "R version 3.5.1 (2018-07-02)"


3) [R] To get Help on specific R commands , objects , functions etchelp(R_Object)  or  ? R_Object

Example Code executed in R-Studio -
> help("mean")

> ?mean

Output of Help will be shown in the Help Window of the R-Studio


4) [R] Finding the Default Working Directory being pointed by your R Environment : getwd()
This is the folder where all your R Scripts will be saved & read from by default.

Example Code executed in R-Studio -
> getwd()
[1] "D:/Personal/Intiglide_DS_Course"                      


5) [R] To Change the Working Directory of your R Environment : setwd(dir_path)

Example Code executed in R-Studio -
> setwd("D:/Personal/Intiglide_DS_Course")   


6) [R] To list all the files & folders in the current directory of R Environment : dir() or  list.files()

Example Code executed in R-Studio -
> list.files()
  [1] "3rd June  class R script.R"                                                               
  [2] "abc_local_radio.csv"                                                                      
  [3] "all.zip"                                                                                  
  [4] "all_stocks_5yr.csv"  
  [5] "Test_Folder" 


7) [R] To list all the files & folders in the current directory of R Environment with certain Pattern: list.files(Pattern='*pattern*')

Example Code executed in R-Studio -
> list.files(pattern = '*Twitter*')
[1] "R file_Twitter_Shashank.txt"                 
[2] "R file_Twitter_Shashank_1.R"                 
[3] "Twitter Data Analysis using rtweet Package.R"
[4] "Twitter Word Cloud in R.R" 


8) [R-Studio Shortcut] To clean the R-Studio console : Press Ctrl + L  in R-Studio Console

9) [R-Studio Shortcut] To retrieve the previous command in R-Studio console : Press 'Up Arrow'  in R-Studio Console

10) [R-Studio Shortcut] To interrupt / stop the currently executing R Command : Press 'Esc key' in R-Studio Console

11) [R] To add Comment / Remarks in R Code / Script   

Comments / Remarks can be added to R Scripts by preceding a statement with '#' symbol
Any statement in the same line after '#' will be ignored by R Interpreter 

Example Code executed in R-Studio -
# This is a comment
> Num_Var_2 <- 11 # This is assignment


12) [R] To Define & Assign a Variable in R  
Variables dont have to be predefined with a DataType
Variables can be dynamically defined during Value Assignment & it takes the Data Type of the Value

There are 3 ways by which Value assignment can be done to a variable 

Example Code executed in R-Studio -
> Num_Var_1 = 11

> Num_Var_2 <- 11

> 13 -> Num_Var_3

First Example above is called 'Assignment using Equal Operator'
Second Example above is called 'Assignment using Leftward Assignment Operator'
Third Example above is called 'Assignment using Rightward Assignment Operator'

R practitioners prefer using the 'Assignment using Leftward Assignment Operator'.


13) [R] To print / show the content of a variable or the output of a R statement  : print(R_Obj_Stmt)

Example Code executed in R-Studio -
> Var_Str <- 'This is a String Variable'
> print(Var_Str)
[1] "This is a String Variable" 


14) [R] To list / show all R objects . functions , variables defined in a R Environment   : ls()

Example Code executed in R-Studio -
> Var_Str <- 'This is a String Variable'
> print(Var_Str)
[1] "This is a String Variable" 


15) [R] To Remove/delete R objects . functions , variables defined in a R Environment   : rm()

Example Code executed in R-Studio -
> Var_3 <- 5 # Defining & Assigning a Variable 
> Var_3      # Displaying the content of the variable 
[1] 5
> rm(Var_3)  # Remove the variable from the Environment
> Var_3      # Displaying the content of the variable 
Error: object 'Var_3' not found

Also , we can selectively Remove specific Objects : rm(object_name)

Also , we can Remove almost all R Objects from a specific R Env by : rm(list=ls())


16) [R]  How to Quit / Exit from R 

> quit() 

or

> q()

17) [R]  How to see 'Structure' of any object in R 

Example 1 :- 
> x <- 1:20  # A numeric vector
> str(x)
 int [1:20] 1 2 3 4 5 6 7 8 9 10 ...

Example 2 :- 
> x_list <- list ( c(1,2,3) , 'String' , list(1,2)) # defining a list
> str(x_list)
List of 3
 $ : num [1:3] 1 2 3
 $ : chr "String"
 $ :List of 2
  ..$ : num 1
  ..$ : num 2

18) [R]  if you don't assign an expression to an R object , R will display the results , but they are also stored in the .Last.value object and the last output can be retrieved by printing the output of .Last.value object .

Example -
> 123 * 35
[1] 4305
> .Last.value
[1] 4305

19) [R]  To get the count of number of elements of any R Data Structures like Vector , list , Matrix , Array etc ; use length() function .

Example 1 -
> a <- 1:15
> a
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
> length(a)
[1] 15

Example 2
 -
> u <- list ( 1:3 ,c('abc' , 'def'),list(1))
> u
[[1]]
[1] 1 2 3

[[2]]
[1] "abc" "def"

[[3]]
[[3]][[1]]
[1] 1

> length(u)
[1] 3

20) [R]  quick way to create a sequence of number vector in R - use ':' or function seq()

Example 1 - to create a vector containing a sequence of numbers between 3 & 15
> num_vector <- 3:15
> num_vector
 [1]  3  4  5  6  7  8  9 10 11 12 13 14 15

Example 2 - to create a vector containing a sequence of numbers from 15 to 3 in reverse order
> num_vector_2 <- 15:3
> num_vector_2 
 [1] 15 14 13 12 11 10  9  8  7  6  5  4  3
>

Example 3 - to create a vector containing a sequence of alternate numbers between 3 & 30
> seq(3,30 , by =2)
 [1]  3  5  7  9 11 13 15 17 19 21 23 25 27 29

21) [R]  Replicate the values of a Vector or List n number of times  : rep()

Example 1 - Replicate / Repeat a Value n number of times 
> rep(2 , 3)
[1] 2 2 2

Example 2 - Replicate / Repeat  Values of Vector n number of times 
> rep(1:4 , 2)
[1] 1 2 3 4 1 2 3 4

Example 3 - Replicate / Repeat  each Value of Vector n number of times 
> rep(1:4 , each = 2)
[1] 1 1 2 2 3 3 4 4

22) [R]  How to Sort the values of a vector : sort()

Example 1 - Default sorting is ascending order
> sort(c(2,7,1,6))
[1] 1 2 6 7

Example 2 - sorting in descending order
> sort(c(2,7,1,6) , decreasing = T)
[1] 7 6 2 1

23) [R]  How to find the position in the vector where the value of the element matches certain value : which()

Example -
> x <- 7:22
> which(x==21)
[1] 15
> x[which(x==21)]
[1] 21

> x <- c(2,2,4,5)
> which(x==2)
[1] 1 2

24) [R]  How to find the maximum of minimum value from a vector  : max() / min()

Example -
> x <- 11:60
> max(x)
[1] 60
> min(x)
[1] 11

25) [R]  to find the position of maximum & minimum value in a vector   : which.max()  , which.min()

Example -
> z
[1] 2 4 2 3 4 1
> which.max(z)
[1] 2
> which.min(z)
[1] 6

26) [R]  to extract the unique values only from a vector / dataframe or array   : unique()

Example -
> z <- c ( 2,4,2,3,4,1)
> unique(z)
[1] 2 4 3 1

27) [R]  to reverse the value of a vector   : rev()

Example -
> z
[1] 2 4 2 3 4 1
> rev(z)
[1] 1 4 3 2 4 2
>

28) [R]  to list all the datasets available in the loaded R Packages   : data()

Example -
> data()

29) [R]  to find the count of number of characters in a String     : nchar()

Example -
> nchar('India')
[1] 5

30) [R]  to list all built in functions in R      : builtins()

Example -
> builtins()

31) [R]  to find the R Home Directory , or the folder path to a component of R installation : R.home()

Example -
> R.home()
[1] "D:/Users/XYZ/Documents/R/R-3.5.1"

> R.home(component = 'readxl')
[1] "D:/Users/XYZ/Documents/R/R-3.5.1/readxl"

32) [R]  to list all the files and folders in a specific Directory  : list.files()  or dir()

Example 1- List all the files & folders in the Current Working Directory of R 
> list.files()

Example 2- List all the files & folders in the subfolder 'Test' within the Current Working Directory of R 
list.files("./Test")

Example 3- List all the files & folders in the subfolder 'Test' within the Current Working Directory of R where the file name contains 'Text' in its name 
> list.files("./Test" , 'Text')


Priyaranjan Mohanty


@AUTHOR : Admin

Tags:Eco, Water, Air, Environment

Comments (0)

    No Comments Found
Leave a Comment