There is a list type of objects in R and the main difference between vector and list is vector collects only certain types of elements like numeric, character, double. Lists can hold any type of elements together.
Generating vectors
> v=c(1,1,2,3,5) > v [1] 1 1 2 3 5 > c("apple", "banana", "melon", "orange") [1] "apple" "banana" "melon" "orange"
We can generate integer elements with sequence generation functions.
> seq.int(1,10) # [1] 1 2 3 4 5 6 7 8 9 10
Random data can also be collected into the vectors.
> runif(5) [1] 0.81286610 0.29486167 0.03254023 0.31721261 0.93284194
Creating time series vectors.
> seq.Date(from=Sys.Date(), to=Sys.Date()+5,by="day") [1] "2016-11-24" "2016-11-25" "2016-11-26" "2016-11-27" "2016-11-28" "2016-11-29"
To assign the vector into the variable.
> assign("vv", c(22,12,23)) > vv [1] 22 12 23
Each element has an index in a vector and we can get the element through its index.
> a=seq.int(20,11) > a [1] 20 19 18 17 16 15 14 13 12 11 > a[3] [1] 18
The 'length' command shows the length of the vector.
> v=seq(-5,5) > length(v) [1] 11 > v [1] -5 -4 -3 -2 -1 0 1 2 3 4 5
The 'typeof' command shows the type of vector.
> m=runif(5) > typeof(m) [1] "double" > m=seq.int(10) > typeof(m) [1] "integer" > m=c("dog","cat") > typeof(m) [1] "character"
To create a vector from input data, we can use the 'scan' command.
> m=scan() 1: 5 2: 34 3: 45 4: Read 3 items > m [1] 5 34 45 >
Some other operations with vectors.
> b=c(3,43,12,29) > sort(b) # sorts vectors elements [1] 3 12 29 43 > rev(b) # provides reverse order [1] 29 12 43 3 > sum(b) # sums up vector [1] 87 > mean(b) # shows mean value [1] 21.75 > which(b>20) # shows element id higher than 20 [1] 2 4 > b[which(b>20)] # shows elements higher than 20 [1] 43 29 > b[b>20] # shows elements higher than 20 [1] 43 29 >
> d=c(20,21,23)
> e=c(1,2)
> append(d, e) # appends two vector elements
[1] 20 21 23 1 2 >
In this tutorial, we've briefly learned about vectors in R.
No comments:
Post a Comment