官术网_书友最值得收藏!

Working with vectors

A vector is one of the basic data structures in R. It contains only similar elements, like strings and numbers, and it can have data types such as logical, double, integer, complex, character, or raw. Let's see how vectors work.

Let's create some vectors by using c():

a<-c(1,3,5,8)
a
## [1] 1 3 5 8

On mixing different objects with vector elements, there is a transformation of the elements so that they belong to the same class:

y <- c(1,3)
class(y)
## [1] "numeric"

When we apply commands and functions to a vector variable, they are also applied to every element in the vector:

y <- c(1,5,1)
y + 3
## [1] 4 8 4

You can use the : operator if you wish to create a vector of consecutive numbers:

c(1:10)
## [1] 1 2 3 4 5 6 7 8 9 10

Do you need to create more complex vectors? Then use the seq() function. You can create vectors as complex as number of points in an interval or even to find out the step size that we might need in machine learning:

seq(1, 5, by=0.1)
## [1] 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 2.1 2.2 2.3 2.4 2.5 2.6
## [18] 2.7 2.8 2.9 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4.0 4.1 4.2 4.3
## [35] 4.4 4.5 4.6 4.7 4.8 4.9 5.0
seq(1, 5, length.out=22)
## [1] 1.000000 1.190476 1.380952 1.571429 1.761905 1.952381 2.142857
## [8] 2.333333 2.523810 2.714286 2.904762 3.095238 3.285714 3.476190
## [15] 3.666667 3.857143 4.047619 4.238095 4.428571 4.619048 4.809524
## [22] 5.000000

The rep() function is used to repeat the value of x, n number of times:

rep(3,20)
## [1] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
主站蜘蛛池模板: 乐清市| 沙雅县| 三明市| 加查县| 斗六市| 南充市| 葫芦岛市| 神农架林区| 信丰县| 扬中市| 隆子县| 福建省| 贺兰县| 墨竹工卡县| 汝州市| 达日县| 黑河市| 荣成市| 苗栗市| 桦川县| 汤阴县| 高州市| 同德县| 饶阳县| 达尔| 富蕴县| 甘谷县| 汪清县| 海盐县| 寿光市| 旺苍县| 沁阳市| 东山县| 梅河口市| 河曲县| 尼勒克县| 精河县| 绥阳县| 石阡县| 连江县| 迁安市|