반응형
(9) 벡터 (Vectors)
벡터는 가장 기본적인 R의 Data Object이다. 우선 기본적으로 6개의 atomic vector들을 알아야할 필요가 있다. 이 6개의 atomic vectors는 이전 포스팅 에도 소개하였지만, logical, integer, double, complex, character, raw이다. 아래의 예를 통해 복습하자.
# Atomic vector of type character. print("abc"); # Atomic vector of type double. print(12.5) # Atomic vector of type integer. print(63L) # Atomic vector of type logical. print(TRUE) # Atomic vector of type complex. print(2+3i) # Atomic vector of type raw. print(charToRaw('hello'))
1. 벡터의 원소에 접근하기
벡터의 원소에는 인덱스를 통해 접근할 수 있다. [](brackets) 이 인덱싱을 위해 필요하다. 인덱싱은 다른 프로그래밍 언어와는 다르게 1부터 시작한다. 또한 - 인덱싱은 해당 엘리먼트를 결과값에서 제외한다는 뜻이다. TRUE, FALSE, 0, 1도 인덱싱을 위해 사용될 수 있다. 아래의 예를 보자.
# Accessing vector elements using position. t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat") u <- t[c(2,3,6)] print(u) # Accessing vector elements using logical indexing. v <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)] print(v) # Accessing vector elements using negative indexing. x <- t[c(-2,-5)] print(x) # Accessing vector elements using 0/1 indexing. y <- t[c(0,0,0,0,0,0,1)] print(y)
[1] "Mon" "Tue" "Fri" [1] "Sun" "Fri" [1] "Sun" "Tue" "Wed" "Fri" "Sat" [1] "Sun"
2. 벡터 조작하기
(1) 벡터 연산
길이가 같은 벡터들은 더하고, 빼고, 곱하고, 나누고 할 수 있다.
# Create two vectors. v1 <- c(3,8,4,5,0,11) v2 <- c(4,11,0,8,1,2) # Vector addition. add.result <- v1+v2 print(add.result) # Vector substraction. sub.result <- v1-v2 print(sub.result) # Vector multiplication. multi.result <- v1*v2 print(multi.result) # Vector division. divi.result <- v1/v2 print(divi.result)
[1] 7 19 4 13 1 13 [1] -1 -3 4 -3 -1 9 [1] 12 88 0 40 0 22 [1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000
(2) 벡터 엘리먼트 재사용
만약 두 개의 벡터를 연산하려는데 길이가 다르면, 짧은 쪽의 벡터의 원소가 재사용된다.
v1 <- c(3,8,4,5,0,11) v2 <- c(4,11) # V2 becomes c(4,11,4,11,4,11) add.result <- v1+v2 print(add.result) sub.result <- v1-v2 print(sub.result)
[1] 7 19 8 16 4 22 [1] -1 -3 0 -6 -4 0
위의 결과를 보면 v2가 (4,11) 에서 (4,11,4,11,4,11)로 바뀌었음을 알 수 있다. 연산을 하기 위해 (4,11)이 재사용된 것이다.
(3) 벡터 엘리먼트 정렬
벡터들의 엘리먼트는 sort() 함수를 통해 정렬될 수 있다.
v <- c(3,8,4,5,0,11, -9, 304) # Sort the elements of the vector. sort.result <- sort(v) print(sort.result) # Sort the elements in the reverse order. revsort.result <- sort(v, decreasing = TRUE) print(revsort.result) # Sorting character vectors. v <- c("Red","Blue","yellow","violet") sort.result <- sort(v) print(sort.result) # Sorting character vectors in reverse order. revsort.result <- sort(v, decreasing = TRUE) print(revsort.result)
[1] -9 0 3 4 5 8 11 304 [1] 304 11 8 5 4 3 0 -9 [1] "Blue" "Red" "violet" "yellow" [1] "yellow" "violet" "Red" "Blue"
반응형
'Tools > R' 카테고리의 다른 글
R - (10) 리스트(List) (0) | 2017.03.04 |
---|---|
R 통계 분석 - 평균, 중앙값, 최빈값 (Mean, Median, Mode) (0) | 2017.02.23 |
R - (8) 문자열 (Strings) (0) | 2017.02.23 |
R을 통한 2017년 대선 주자들 페이스북 분석 (5) | 2017.02.21 |
R - (7) 함수 (0) | 2017.02.19 |