Site de Jean-Michel RICHER

Maître de Conférences en Informatique à l'Université d'Angers

Ce site est en cours de reconstruction certains liens peuvent ne pas fonctionner ou certaines images peuvent ne pas s'afficher.


7.1. Operations on Vectors

In this section you will find more information about how to compose operations with vectors.

7.1.1. Select elements

# define persons
> persons <- c("John", "Jack", "Bill", "Kim", "Jason", "Michael", "Britney", "Julia")
> length(persons)
[1] 8
 
# select persons from numeric index 4 to 6
> persons[c(4:6)]
[1] "Kim"     "Jason"   "Michael"
 
# select using a vector of booleans
# here NA (Not Available) tells us that we have tried to select more
# data than available: persons contains 8 values and the boolean 
# selection uses 10 values
> persons[c(rep(TRUE,2),rep(FALSE,3),rep(T,5))]
[1] "John"    "Jack"    "Michael" "Britney" "Julia"   NA        NA 

7.1.2. Name elements

> weights <- c(77, 58, 66, 82)
 
# assign names to numeric values
> names(weights) <- c("John", "Jack", "Bill", "Kim")
 
> weights
John Jack Bill  Kim 
  77   58   66   82 
 
# select using one name
> weights["Bill"]
Bill 
  66 
 
# select using several names  
> weights[c("John","Bill")]
John Bill 
  77   66 

7.1.3. Arithmetic operations and comparisons

> weights <- c(77, 58, 66, 82)
> names(weights) <- c("John", "Jack", "Bill", "Kim")
> weights
John Jack Bill  Kim 
  77   58   66   82 
 
# add one to all values of weight
> weights+1
John Jack Bill  Kim 
  78   59   67   83 
 
# add vector (10,20) 
# so we get 77+10, 58+20, 66+10, 82+20  
> weights+c(10,20)
John Jack Bill  Kim 
  87   78   76  102 
 
# which values are greater than 68  
> weights > 68
 John  Jack  Bill   Kim 
 TRUE FALSE FALSE  TRUE
 
# use operator x %in% v (is x inside vector v) 
> 77 %in% weights        
[1] TRUE
 

7.1.4. Sort, order

The function sort() will sort the data and order() will return the order of the index if the data are sorted.

> weights <- c(85,78,54,98,66,78,77,62,89,92,76,77,55,68);
> sort(weights)
 [1] 54 55 62 66 68 76 77 77 78 78 85 89 92 98
> sort(weights[3:8])
[1] 54 62 66 77 78 98
> order(weights)
 [1]  3 13  8  5 14 11  7 12  2  6  1  9 10  4

7.1.5. Sum, mean, median, min, max, quantile, var, sd, summary

> weights <- c(85,78,54,98,66,78,77,62,89,92,76,77,55,68);
> sum(weights)
[1] 1055
> mean(weights)
[1] 75.35714
> var(weights)     # variance
[1] 175.3242
> sd(weights)      # standard deviation
[1] 13.241
> median(weights)
[1] 77
> min(weights)
[1] 54
> max(weights)
[1] 98
> quantile(weights)
   0%   25%   50%   75%  100% 
54.00 66.50 77.00 83.25 98.00 
> summary(weights)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  54.00   66.50   77.00   75.36   83.25   98.00