0% found this document useful (0 votes)
16 views12 pages

Creating and Manipulating Objects

The document provides an overview of object types in R programming, including vectors, lists, matrices, factors, arrays, and data frames, detailing their characteristics and examples of usage. It also explains how to manipulate objects using functions like edit(), append(), and remove(), as well as how to convert data types and access values through indexing. Additionally, it covers naming objects and accessing specific variables within data objects.

Uploaded by

gjob54530
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views12 pages

Creating and Manipulating Objects

The document provides an overview of object types in R programming, including vectors, lists, matrices, factors, arrays, and data frames, detailing their characteristics and examples of usage. It also explains how to manipulate objects using functions like edit(), append(), and remove(), as well as how to convert data types and access values through indexing. Additionally, it covers naming objects and accessing specific variables within data objects.

Uploaded by

gjob54530
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Objects

Every programming language has its own data types to store values or any information so
that the user can assign these data types to the variables and perform operations
respectively. Operations are performed accordingly to the data types.
These data types can be character, integer, float, long, etc. Based on the data type,
memory/storage is allocated to the variable..
Unlike other programming languages, variables are assigned to objects rather than data
types in R programming.
Type of Objects
There are 5 basic types of objects in the R language:
Vectors
Atomic vectors are one of the basic types of objects in R programming. Atomic vectors can
store homogeneous data types such as character, doubles, integers, raw, logical, and
complex. A single element variable is also said to be vector.
Example:

# Create vectors

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

y <- c("a", "b", "c", "d")

z <- 5

# Print vector and class of vector

print(x)

print(class(x))

print(y)

print(class(y))

print(z)

print(class(z))

Output:
[1] 1 2 3 4
[1] "numeric"
[1] "a" "b" "c" "d"
[1] "character"
[1] 5
[1] "numeric"
Lists
List is another type of object in R programming. List can contain heterogeneous data types
such as vectors or another lists.
Example:

# Create list

ls <- list(c(1, 2, 3, 4), list("a", "b", "c"))

# Print

print(ls)

print(class(ls))

Output:
[[1]]
[1] 1 2 3 4

[[2]]
[[2]][[1]]
[1] "a"

[[2]][[2]]
[1] "b"

[[2]][[3]]
[1] "c"

[1] "list"
Matrices
To store values as 2-Dimensional array, matrices are used in R. Data, number of rows and
columns are defined in the matrix() function.
Syntax:
matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
Example:

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

# Create matrix

mat <- matrix(x, nrow = 2)

print(mat)

print(class(mat))

Output:
[, 1] [, 2] [, 3]
[1, ] 1 3 5
[2, ] 2 4 6

[1] "matrix"
Factors
Factor object encodes a vector of unique elements (levels) from the given data vector.
Example:

# Create vector

s <- c("spring", "autumn", "winter", "summer",

"spring", "autumn")

print(factor(s))

print(nlevels(factor(s)))

Output:
[1] spring autumn winter summer spring autumn
Levels: autumn spring summer winter
[1] 4
Arrays
array() function is used to create n-dimensional array. This function takes dim attribute as
an argument and creates required length of each dimension as specified in the attribute.
Syntax:
array(data, dim = length(data), dimnames = NULL)
Example:

# Create 3-dimensional array

# and filling values by column

arr <- array(c(1, 2, 3), dim = c(3, 3, 3))

print(arr)

Output:
,, 1

[, 1] [, 2] [, 3]
[1, ] 1 1 1
[2, ] 2 2 2
[3, ] 3 3 3,, 2

[, 1] [, 2] [, 3]
[1, ] 1 1 1
[2, ] 2 2 2
[3, ] 3 3 3,, 3

[, 1] [, 2] [, 3]
[1, ] 1 1 1
[2, ] 2 2 2
[3, ] 3 3 3

Data Frames
Data frames are 2-dimensional tabular data object in R programming. Data frames consists
of multiple columns and each column represents a vector. Columns in data frame can have
different modes of data unlike matrices.
Example:
# Create vectors

x <- 1:5

y <- LETTERS[1:5]

z <- c("Albert", "Bob", "Charlie", "Denver", "Elie")

# Create data frame of vectors

df <- data.frame(x, y, z)

# Print data frame

print(df)

Output:
xy z
1 1 A Albert
22B Bob
3 3 C Charlie
4 4 D Denver
55E Elie

Manipulating Objects
Objects can be manipulated by using several functions.

Modify Objects
edit() function will invokes a text editor on an R object
 edit() works with any type of object
o Vector
o List
o Matrix
o Data Frame
o 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


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()
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
#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
ls()
[1] "a" "b" "c" "d" "newData" "trees"
If we want to delete ‘b’ and ‘trees’ objects
rm("b", "trees")
ls()
[1] "a" "c" "d" "newData"
If we want to remove all the objects in R, use rm(list =ls())
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
#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”

Converting Objects

type.convert() function in R Language is used to compute the data type of a particular data
object.
It can convert data object to logical, integer, numeric, or factor.
Syntax: type.convert(x)
Parameter:
x: It can be a vector matrix or an array
Example 1: Apply type.convert to vector of numbers

# R program to illustrate

# type.convert to vector of numbers

# create an example vector

x1 <- c("1", "2", "3", "4", "5", "6", "7")

# Apply type.convert function

x1_convert <- type.convert(x1)

# Class of converted data

class(x1_convert)

Output:
[1] "integer"
Here in the above code, we can see that before type.convert() function all the numbers are
stored in it, but still its a character vector. And after the function it became “Integer”.
Example 2: Type conversion of a vector with both characters and integers.

# R Program to illustrate
# conversion of a vector with both characters and
integers

# create an example vector

x1 <- c("1", "2", "3", "4", "5", "6", "7")

# Create example data

x2 <- c(x1, "AAA")

# Class of example data

class(x2)

# Apply type.convert function

x2_convert <- type.convert(x2)

# Class of converted data

class(x2_convert)

Output:
[1] "character"
[1] "factor"
Here, in the above code there were some characters and some integers after using
type.convert() function. So, the output comes to be a factor.

Accessing the value of an object Using Index

There are multiple ways to access or replace values in vectors or other data structures. The
most common approach is to use “indexing”. This is also referred to as “slicing”.
Brackets [ ] are used for indexing.

Here are some examples that show how elements of vectors can be obtained by indexing.

b <- 10:15
b
## [1] 10 11 12 13 14 15
Get the first element of a vector
b[1]
## [1] 10
Get elements 2 and 3

b[2:3]
Now a more advanced example, return all elements except the second

b[c(1,3:6)]
You can also use an index to change values

b[1] <- 11

Accessing the values of an object with names


names() function in R Language is used to get or set the name of an Object. This function
takes object i.e. vector, matrix or data frame as argument along with the value that is to be
assigned as name to the object. The length of the value vector passed must be exactly equal
to the length of the object to be named.
Syntax: names(x) <- value
Parameters:
x: Object i.e. vector, matrix, data frame, etc.
value: Names to be assigned to x
Example 1:

# R program to assign name to an object

# Creating a vector

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

# Assigning names using names() function

names(x) <- c("gfg1", "gfg2", "gfg3", "gfg4", "gfg5")

# Printing name vector that is assigned

names(x)

# Printing updated vector

print(x)

Output:
[1] "gfg1" "gfg2" "gfg3" "gfg4" "gfg5"
gfg1 gfg2 gfg3 gfg4 gfg5
1 2 3 4 5
Accessing Specific Variables in an Object

Accessing a particular variable (i.e., column) in a data object is


simple: DataObject$VarName , where DataObject is the data object and VarName the
variable desired. The $ (dollar) symbol is how R links the requested variable to the data
object. A single accessed variable is returned as a vector.

# access variable=sex in object m1

print(m1$sex)

You might also like