R 101: Vectors

[This article was first published on Mathew Analytics LLC » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Vectors are a basic data structure in R and are created using the c()
function. Unlike data frames and lists, the elements of a vector must be of
the same mode.

Functions can be used on a vector. For example, length(x) can be used to find the number of elements in x. Furthermore, conditions can be used to determine if the elements of a vector meet a certain criteria.

The elements of a vector can be selected by using the name of the vector
followed by an index vector in square brackets. Positive index values specify
the values to be included. Negative index values specifiy the values to be
excluded. Furthermore, vectors with a names attribute can be indexed using
its names.

# Creating vectors with the c() function
vecone <- c(1,3,5,7,9)
vectwo <- c(“KS”, “IA”, “NY”, “NY”, “FL”)
vecthree <- c(vecone, 0, vecone)

mode(vecone)
mode(vectwo)
mode(vecthree)

# Using functions on a vector
length(vecone)
length(vectwo)
length(vecthree)

max(vecone)
min(vecone)

# Vector arithmetic
vecone + vecone
vecone * 2
vecone^2

# Using conditions
vecon > 4
vecone > 4 & vecone < 9
vectwo == “KS”
vectwo != “KS”
vectwo[vectwo != “KS”]
which(vectwo != “KS”)
vectwo[c(2,3,4,5)]

# Indexing a vector
vecone
vectwo
vecone[1]
vectwo[1]
vecone[3]
vectwo[3]
vecone[1:3]
vectwo[1:3]
vecone[length(vecone)]
vectwo[length(vectwo)]

vecone[-2]
vectwo[-2]
vecone[-c(1:3)]
vectwo[-c(1:3)]
vecone[-length(vecone)]
vectwo[-length(vectwo)]

# Indexing a vector with names
newvec <- c(1,6,8,9,13,14)
names(newvec) <- c(“Var1″, “Var2″, “Var3″, “Var4″, “Var5″, “Var6″)
newvec
newvec[“Var3”]
newvec[c(“Var1”, “Var3”, “Var6”)]

To leave a comment for the author, please follow the link and comment on their blog: Mathew Analytics LLC » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)