2011년 4월 7일 목요일

R - 데이터 타입 (Data Types)

참고: http://www.statmethods.net/input/datatypes.html

심플하게 정리하면.. 

1) vectors (numerical, character, logical)
  - 그냥 벡터.
  - 벡터안의 모든 값은 같은 종류여야 한다. 

a <- c(1,2,5.3,6,-2,4) # numeric vector
b <- c("one","two","three") # character vector
c <- c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE) #logical vector




2) matrices
  - 2차원 메트릭스 
  - 메트릭스의 모든 컬럼은 같은 종류(mode)이여야 하고, 길이가 같아야 한다. 

# generates 5 x 4 numeric matrix 
y<-matrix(1:20, nrow=5,ncol=4)

# another example
cells <- c(1,26,24,68)
rnames <- c("R1", "R2")
cnames <- c("C1", "C2") 
mymatrix <- matrix(cells, nrow=2, ncol=2, byrow=TRUE,
  dimnames=list(rnames, cnames))




3) arrays
  - 메트릭스랑 비슷한데, 2차원(dimensions)이상을 가질수 있다. 


4) dataframe
  - SAS에서 dataset과 비슷
  - 그냥 DB table이라고 생각하면 편할듯.
  - dataframe의 각 컬럼은 다른 종류(mode)의 값을 가질수 있다. 

d <- c(1,2,3,4)
e <- c("red", "white", "red", NA)
f <- c(TRUE,TRUE,TRUE,FALSE)
mydata <- data.frame(d,e,f)
names(mydata) <- c("ID","Color","Passed") # variable names




4) lists
  - an ordered collection of objects
  - python의 dictionary와 거의 유사
  - list(a="Fred", ...) 라고 하면, a가 key가 아니라 이름이고, 이름은 안써도 되고, 이름이 있건없건 간에 위치로 참조 가능하다...

# example of a list with 4 components - 
# a string, a numeric vector, a matrix, and a scaler 
w <- list(name="Fred", mynumbers=a, mymatrix=y, age=5.3)

# example of a list containing two lists 
v <- c(list1,list2)




5) fators
  - 변수를 nominal 형태로 만들때.. 

# variable gender with 20 "male" entries and 
# 30 "female" entries 
gender <- c(rep("male",20), rep("female", 30)) 
gender <- factor(gender) 
# stores gender as 20 1s and 30 2s and associates
# 1=female, 2=male internally (alphabetically)
# R now treats gender as a nominal variable 
summary(gender)



기타.

Useful Functions

length(object) # number of elements or components
str(object)    # structure of an object 
class(object)  # class or type of an object
names(object)  # names

c(object,object,...)       # combine objects into a vector
cbind(object, object, ...) # combine objects as columns
rbind(object, object, ...) # combine objects as rows 

object     # prints the object

ls()       # list current objects
rm(object) # delete an object

newobject <- edit(object) # edit copy and save as newobject 
fix(object)               # edit in place 



댓글 없음:

댓글 쓰기