R Manipulating Objects
Manipulating Objects
The following commands are used to View objects that are available in the workspace
Syntax
//Syntax:
objects()
ls()
both the syntax provide the same result
Modify Objects
edit() function will invokes a text editor on an R object
- edit() works with any type of object
- Vector
- List
- Matrix
- Data Frame
- Factor
Consider an object newData
edit(newData) invokes an editor in which the data can be modified. The example shown illustrates the same
Syntax
modData <- edit(newData)
Data Editor window will pop up and data can be edited in the same window. For vectors, lists and factors, a notepad will pop up.
append() function adds elements to a vector
Syntax
//Syntax:
append(x, value, after = length(x))
Where,
x: the vector
value: the value to be appended
after: the position after which the element has to be appended
CODE/PROGRAM/EXAMPLE
newVar <- c(11,25,32,22,44,25,43,22)
append(newVar, 99, after = 4)
[1] 11 25 32 22 99 44 25 43 22
append(newVar, 99, after = 5)
[1] 11 25 32 22 44 99 25 43 22
The value is placed, based on the position in the syntax Additional elements can be appended at the end of an object by using the concatenation command c()
CODE/PROGRAM/EXAMPLE
x <- 1:10
x
[1] 1 2 3 4 5 6 7 8 9 10
x <- c(x, 11:20)
x
[1] 1 2 3 4 5 6 7 8 9 10
[11] 11 12 13 14 15 16 17 18 19 20
# The values will be appended at the end
An element can be removed from an object by prefixing its index position with the minus (‘-’) symbol
CODE/PROGRAM/EXAMPLE
#removing 11 from x
x <- x[-11]
print(x)
[1] 1 2 3 4 5 6 7 8 9
[10] 10 12 13 14 15 16 17 18 19
[19] 20
Delete Objects
remove() and rm() can be used to remove objects. These can be specified successively as character strings or in the character vector list or through a combination of both. All objects thus specified will be removed
Consider the following objects in R
CODE/PROGRAM/EXAMPLE
ls()
[1] "a" "b" "c" "d" "newData" "trees"
If we want to delete ‘b’ and ‘trees’ objects
CODE/PROGRAM/EXAMPLE
rm("b", "trees")
ls()
[1] "a" "c" "d" "newData"
If we want to remove all the objects in R, use rm(list =ls())
CODE/PROGRAM/EXAMPLE
rm(list=ls())
#Now lets check, by using ls() command
ls()
[1] character(0)
All the objects created can be saved and accessed later by using save.image() and load() functions
CODE/PROGRAM/EXAMPLE
#Consider a matrix Object ‘x’
x
Jane Tom Katy James
[1,] 99.0 99.8 99.4 98.3
[2,] 96.0 98.3 99.2 99.1
[3,] 99.2 99.7 98.9 99.9
#Saving the existing objects
setwd("D:/R/")
save.image(file = "saveObjects.RData")
#Now lets delete this object
rm(x)
#Check if the object exists
print(x)
Error in print(x) : object ‘x’ not found
#Now lets get the value back
load(file = "saveObjects.RData")
#Check if the object x exists
print(x)
Jane Tom Katy James
[1,] 99.0 99.8 99.4 98.3
[2,] 96.0 98.3 99.2 99.1
[3,] 99.2 99.7 98.3 99.9
When saving the file, extension must be “.RData”