Type
-
Atomic Vector
logical
integer
double
character
#to name the vector
> c(x=1,y=4,"father"=8)
x y father
1 4 8
-
List
#use `str()` to show the exact content of a list
> list(1:2,5,"a")
[[1]]
[1] 1 2
[[2]]
[1] 5
[[3]]
[1] "a"
> list(1:2,5,"a") %>% str()
List of 3
$ : int [1:2] 1 2
$ : num 5
$ : chr "a"
#a list can be named and contain other lists
> list(a=1,b=3) %>% str()
List of 2
$ a: num 1
$ b: num 3
> list(list(1:2,NA),list(1:10)) %>% str()
List of 2
$ :List of 2
..$ : int [1:2] 1 2
..$ : logi NA
$ :List of 1
..$ : int [1:10] 1 2 3 4 5 6 7 8 9 10
Subsetting
#use `[]`
> x <-c(1,2,3,4,5)
> x[1]
[1] 1
> x[c(1,2,3)]
[1] 1 2 3
> x[c(-1,-2)]
[1] 3 4 5
> x[x%%2==0]
[1] 2 4
#in terms of lists,`[]`derives a new list and `[[]]` derives a vector
a <- list(a= 1:3,b="asoul",c=pi,d=list(-1,-5))
> str(a)
List of 4
$ a: int [1:3] 1 2 3
$ b: chr "asoul"
$ c: num 3.14
$ d:List of 2
..$ : num -1
..$ : num -5
> str(a[1])
List of 1
$ a: int [1:3] 1 2 3
> str(a[[1]])
int [1:3] 1 2 3
> str(a[[4]][1])
List of 1
$ : num -1
> str(a[[4]][[1]])
num -1
> str(a$a)
int [1:3] 1 2 3
#tibble is special form of list,as all the vectors that consist of it have the same length;it can be applied to the same orders
> tibble(a=1:5,b=3:7)
# A tibble: 5 x 2
a b
<int> <int>
1 1 3
2 2 4
3 3 5
4 4 6
5 5 7
> b <- tibble(a=1:5,b=3:7)
> b[[1]]
[1] 1 2 3 4 5
> b[[2]]
[1] 3 4 5 6 7
> b[["b"]]
[1] 3 4 5 6 7
> b$b
[1] 3 4 5 6 7
> b[1]
# A tibble: 5 x 1
a
<int>
1 1
2 2
3 3
4 4
5 5
> b[1,]
# A tibble: 1 x 2
a b
<int> <int>
1 1 3
Function
typeof :denotes the type of a vector
length :denotes the number of elements of a vector
as.* :force to transform the type of a vector(for example:as.character(),as.integer())
runif :give a series of values derived from a unifrom distribution(the first parameter is the number of values,the second lower limit,the third upper limit,and the latter two ones are by default 0 and 1)
rnorm :give a series of values derived from a normal distribution(the first parameter is the number of values,the second mean,the third standard deviation,and the latter two ones are by default 0 and 1)
rep:
> rep(1:2,2)
[1] 1 2 1 2
> rep(1:2,each=2)
[1] 1 1 2 2
sample :to sample(the first parameter is the dataset,the second the times,the third T or F which denotes sampling with replacement when choosing T and F without(by default));for example,`sample(100,10)` generates 10 numbers no smaller than 1 and no bigger than 100,`sample(c("T","H"),1)` generates "T" or "F"(just like flipping a coin)