Skip to content

Instantly share code, notes, and snippets.

@prasoonsharma
Created November 27, 2010 11:15
Show Gist options
  • Save prasoonsharma/717808 to your computer and use it in GitHub Desktop.
Save prasoonsharma/717808 to your computer and use it in GitHub Desktop.
Vector operations in R
# VECTOR OPERATIONS IN R
# Create vectors
age <- c(28, 19, 29, 81, 60, 55, 44, 23)
year <- 1990:1995 # notice the use of : operator for sequence function (seq)
five.ones <- rep(1, 5) # checkout the use of repeat function
# a vector of odd numbers between 1 and 100
odd.numbers <- seq(1, 100, by=2)
?seq
# ----------------------------------
# Accessing elements of vector
# get one element
age[2]
# get multiple elements (subset)
odd.numbers[1:20]
odd.numbers[c(1,10,20)]
# get elements that pass a test
age[age > 55]
# ----------------------------------
# Vector properties
# length
length(odd.numbers)
# summary stats
summary(age)
# structure
str(age)
# ----------------------------------
# Manipulate vector
# set value
age[2] <- 99
# reverse vector
rev(age)
# sort
sort(age)
# reverse sort
sort(age, decreasing=T)
# apply math functions
age * 2
year + 2
# ----------------------------------
# Apply stats functions to vector
# max
max(age)
# min
min(age)
# mean
mean(age)
# median
median(age)
# sum
sum(age)
# variance
var(age)
# rank
rank(age)
# ----------------------------------
# Test for vector
is.vector(age)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment