Indexing

Published by onesixx on

https://onesixx.com/vector/
names()    for vector, list

rownames()  colnames() for 2d

> a
 a  b  c  d  e  f  g  h  i  j 
 1  2  3  4  5  6  7  8  9 10 

> names(a==6)
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

> names(a[a==6])
[1] "f"

> a[a==6]
f 
6 

> which(a == 6)
f 
6 

> a==6
    a     b     c     d     e     f     g     h     i     j 
FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE 

> a==6 %>% names()
logical(0)
Browse[3]> a[T,F]
Error in a[T, F] : incorrect number of dimensions
Browse[3]> a[T,F,f,f,f,f,f,f,f,f]
Error: object 'f' not found
Browse[3]> a[c(T,F,F,F,F,F,F,F,F,F)]
a 
1 
http://www.cyclismo.org/tutorial/R/vectorIndexing.html
http://www.dummies.com/how-to/content/how-to-get-values-out-of-vectors-in-r.html
library(tidyverse)

i <- c(1:7)
c <- LETTERS[i]
n <- c(-3,-2,-1,0,1,2,3) 
l <- c(TRUE,FALSE,FALSE,TRUE,FALSE,FALSE,FALSE)
f <- c("MALE","FEMALE","MALE","FEMALE","FEMALE","MALE","MALE") %>% as.factor

d.mx <- cbind(i,c,n,l,f)
d.df <- d.mx %>% as.data.frame
d.lt <- list(i,d.mx,d.df)

[] Indexing (sub-setting)

Indexing: Vector의 개별 요소를 가리키는 것, 즉 데이터의 일부분을 선택/선별하는 작업
                     대괄호[]를 안에 위치 정보에 해당되는 Vector를 입력하면,  원래 Vector의 특정 위치 값만 sub-setting

, 전후 아무값도 입력하지 않은 모든 행과 열을 의미

 [행,] 또는 [,열]

[-] 특정위치 값 제외

[] 안에 Vector 입력 시 마이너스(-) 표시를 사용하면, 입력한 값의 위치에 있는 인자를 제외하고 sub-setting

특정위치에 값 추가/ 변경

n[3] <- 6 으로  3th값을 -1에서 6으로 변경가능하고, n[8]<- 6 으로 마지막에 값을 추가할 수 있다. 

T, F를 활용한 Indexing

> a <- c(1,2,3,4,5) #define a vector of data
> b <- c(T,F,F,T,F) #define a vector made up of logical values
> a[b]
[1] 1 4

dataframe일때, 한 값만 쓰면 열우선

df[3]은 세번째 열

Logical Expression 

 ‘|’ 는 항끼리의 vector연산
‘||’ 는 전체 연산 , 결과는 TRUE또는 FALSE하나

> (c(TRUE,TRUE))|(c(FALSE,TRUE))
[1] TRUE TRUE
> (c(TRUE,TRUE))||(c(FALSE,TRUE))
[1] TRUE

> (c(TRUE,TRUE))&(c(FALSE,TRUE))
[1] FALSE  TRUE
> (c(TRUE,TRUE))&&(c(FALSE,TRUE))
[1] FALSE

[조건, ], [조건, 열]  

행 위치정보를 입력하는 곳특정 열에 대한 선택조건을 입력하면,   조건에 부합하는 행들의 선택된 열로 구성된 새로운 데이터 프레임을 생성할 수도 있다.

> d.df[(i>3),]
  i c n     l f
4 4 D 0  TRUE 1
5 5 E 1 FALSE 1
6 6 F 2 FALSE 2
7 7 G 3 FALSE 2

> d.df[(i>4),c("i","l")]
  i     l
5 5 FALSE
6 6 FALSE
7 7 FALSE
 

마지막 값

https://stackoverflow.com/questions/77434/how-to-access-the-last-value-in-a-vector

  • x[length(x)]
  • mylast(x), where mylast is a C++ function implemented through Rcpp,
  • tail(x, n=1)
  • dplyr::last(x)
  • x[end(x)[1]]]
  • rev(x)[1]

Categories: Reshaping

onesixx

Blog Owner