Introduction to R (Part 2) Data types in R

#########DATA TYPES##########
#mainly six (6) types
#Type 1: Vector
##Six types of vector:logical(T/F),numeric, integer, complex, charater
a=TRUE #logical
b=FALSE #logical
c=20.5 #numeric
d=7L #integer #L to mention integer
e=10+5L #comples
f=”Research HUB” #charater

vec= c(1,4,3,7,90,30,40) #to create a vector
vec
vec2=c(“hello”, “sorry”, “buzinga”)
vec2

sortvec=sort(vec) #sorted from small to large
sortvec

sortvec2=sort(vec2) #sorted alphabatically
sortvec2

vec[4] #gives the vaue in 4th column
vec[3:7] #gives value from 3rd to 7th column
vec[-5] #gives everythingexcept the value in 5th column

vec[3]=10 #replaces the value in the 3rd column
vec

vec[10]=17 #we have a vector range 1:7, can we put 17 in the 10th? YES
vec

 

#Type 2: Lists
##we can have anytype of data in lists
vec3=c(“hello”, 4, TRUE, 7L)
class (vec3) #class gives the vector data type
#we see that all value is converted into “character” type
list1=list(“hello”, 4, TRUE, 7L)
list1 #each value is preserved with its original data type

list2=list(“today”, 10, FALSE, 15L)
list2

list3=merge(list1,list2) #to merge lists
list3

list4=c(list1,list2) #we can simply combine them
list4

list4[5] #extract a value from the list

 

#Type 3: Arrays
##Helps to store data in more than two dimensions
###Usually takes vectors as input parameter
vec5=c(10,3,4,5,7)
vec6=c(30,23,24,54,23,21)

arr=array(c(vec5))
arr

arr2=array(c(vec5, vec6), dim=c(5,5,3)) #make multidimensional vectors
arr2 #gives 5 columns, 5 rows and 3 sets

 

#Type 4: Matrices
##Two dimensional rectangles
help(matrix)

vec7=c(10,3,4,5,7)
vec8=c(30,23,24,54,23)

mat1=matrix(c(vec7,vec8),5,5) #make sure that number of rows and colums are multiple or sub-multiple of present in that vector
mat1

 

#Type 5: Factors
##used to categorize the data and store it as levels
###both strings and integers
vec9=c(34,27,24,50,70, 27)

fvec9=factor(vec9) # to create a factor
fvec9 #gives unique values

 

#Type 6: Data Frame
##a table or two-dimensional array in which each column represents values of one variable
##and each row represents one set of values for each colunm.
stud_id=c(1:5)
stud_name=c(“Stine”, “Amy”, “Munim”,”Marit”,”Erik”)
fun_index=c(98,78,88,82,75) #please don’t mind 😉

stud.data=data.frame(stud_id,stud_name, fun_index) #to create data frame
stud.data #to print created data frame

###########################################################

Leave your thoughts

ResearchHUB

A platform to support academics particularly young researchers. ResearchHUB provides training on different research methods, and academic writing and publishing in peer-reviewed journals.

Team ResearchHUB

Privacy Policy

NEWSLETTER