Introduction to R language: a study of vector

Posted by hbuchel on Sat, 22 Feb 2020 16:46:41 +0100

R language is mainly used for statistics, so the introduction of the concept of vector will make better statistical calculation. In other languages that cannot introduce vector, they will use cycles to calculate some large-scale data, which is not needed in R language. Let's see the specific usage of vector in R language!

First of all, if we take x as a vector and assign it as a vector with five elements, the code is as follows:

> x <- c(1,2,3,4,5)
> x
[1] 1 2 3 4 5
>

We can see that the value of x has become 1,2,3,4,5, in which when we assign vectors, we use the vectorization of C() function. Of course, a vector doesn't have only numbers in it, just like mathematics, but can have Boolean values and strings. Here is an example of an input string vector:

y <- c("one","two","three")
> y
[1] "one"   "two"   "three"
> print(y)
[1] "one"   "two"   "three"

Boolean value:

> z <- c(TRUE,T,F)
> z
[1]  TRUE  TRUE FALSE

You can also directly use the C function to output each number one by one:

> c(1:100)
  [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
 [18]  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34
 [35]  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51
 [52]  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68
 [69]  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85
 [86]  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100

Here, the colon represents output from 1 to 100 one by one. If you want to change the output sequence with the equal difference of 1, you can change the equal difference to 2. The output method is:

> seq (from=1,to=100,by=2)
 [1]  1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45
[24] 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91
[47] 93 95 97 99

You can also change the value of equal difference to 10, or use length.out to limit how many values are output within the specified range, as follows:

> seq (from=1,to=100,by=10)
 [1]  1 11 21 31 41 51 61 71 81 91
> seq (from=1,to=100,length.out = 10)
 [1]   1  12  23  34  45  56  67  78  89 100

Copy the vector, repeat 2 5 times:

> rep(2,5)
[1] 2 2 2 2 2

Repeat x 5 times:

> x
[1] 1 2 3 4 5
> rep(x,5)
 [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

Repeat each number in the x vector 5 times, and then repeat again:

> rep(x,each=5)
 [1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5
> rep(x,each=5,times=2)
 [1] 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 1 1 1 1 1 2 2 2 2
[35] 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5

Use the mode() function to measure the type of object:

> mode(x)
[1] "numeric"

Operate on two different vectors:

> x <- c(1,2,3,4,5)
> y <- c(6,7,8,9,10)
> x*2+y
[1]  8 11 14 17 20

Find the value in the X vector:

> x[x>3]
[1] 4 5

Understand.

Topics: R Language