Vector

Published by onesixx on

https://onesixx.com/indexing/
https://onesixx.com/%eb%8d%b0%ec%9d%b4%ed%84%b0-%ea%b5%ac%ec%a1%b0-%ec%9c%a0%ed%98%95/

Vector란

  • 하나의 vector의 element는 모두 같은 datatype을 가진다. 
    –  Numeric vector     c(1, 3, 6, 9)
    –  Character vector   c(“가”, “B”, “1” )
    –  Logical vector         c(T,F,FALSE,TRUE) > wrong <- c(1, TRUE, “A”) > wrong %>% class [1] “character”
  • vector의 element는 추가/삭제 불가
    재할당을 통해 추가/삭제
  • 연산시, 길이는 자동을 맞춰진다.  > AA <- c(6) > BB <- c(1:10) > CC <- AA+BB [1] 7 8 9 10 11 12 13 14 15 16 > CC[6] [1] 12

Vector 생성

concatenate :   c()  

> c(1, 6, 9)
[1] 1 6 9

sequence :    seq() 

ex) seq(6, 36, 4)는 6에서 4간격으로 36을 넘기 전 34까지 포함

> seq(from=6, to=36, by=4)
[1] 6 10 14 18 22 26 30 34

ex) seq(3, 10)는 3:10와 같다

> seq(3,10)
> 3:10
[1] 3 4 5 6 7 8 9 10

replicate : rep() 

1번째 인자를 2번째 인자만큼씩 반복해서 Vector생성

> vec <-c(3,6,9)
> rep(vec,2)
[1] 3 6 9 3 6 9

> rep(vec, 2:4)
[1] 3 3 6 6 6 9 9 9 9

> rep(vec, c(3, 1, 5))
[1] 3 3 3 6 9 9 9 9 9

> rep(3, c(1,2,3))
Error in rep(3, c(1, 2, 3)) : invalid 'times' argument

ETC 

> month.name[1:12]
[1] "January" "February" "March" "April"
[5] "May" "June" "July" "August"
[9] "September" "October" "November" "December"

> month.abb[1:12]
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"

> LETTERS[1:26]
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N"
[15] "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"

> letters[1:26]
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n"
[15] "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"

Vector Equality

https://www.oreilly.com/library/view/the-art-of/9781593273842/ch02s10.html

두 vector가 서로 같은지 알고 싶다.
기본적으로  ==로는 vector equality를 판별할수 없다.

> x <- 1:3
> y <- c(1,3,4)
> x == y
[1]  TRUE FALSE FALSE

What happened? The key point is that we are dealing with vectorization.
Just like almost anything else in R, == is a function.

> "=="(3,2)
[1] FALSE
> i <- 2
> "=="(i,2)
[1] TRUE

In fact, == is a vectorized function.
The expression x == y applies the function ==() to the elements of x and y.
yielding a vector of Boolean values.

What can be done instead? One option is to work with the vectorized nature of ==, applying the function all():

> x <- 1:3
> y <- c(1,3,4)
> x == y
[1]  TRUE FALSE FALSE
> all(x == y)
[1] FALSE

Applying all() to the result of == asks whether all of the …

> all(c(1,2) == c(1,2))
[1] TRUE
> all(c(1,2) != c(1,2))
[1] FALSE
> all(c(1,2) == c(2,1))
[1] FALSE

Categories: R Reshaping

onesixx

Blog Owner