DBILITY

R type casting ( 데이터 형 변환 ) 본문

statistics/R

R type casting ( 데이터 형 변환 )

DBILITY 2018. 11. 23. 14:29
반응형

데이터 타입의 확인은 class()와 str()함수를 사용할 수 있다.

> as.vector(1)
[1] 1
> class(as.vector(1))
[1] "numeric"
> c(1)
[1] 1
> class(c(1))
[1] "numeric"
> x<-c(1,2,3)
> y<-c(4,5,6)
> z<-c('a','b','c')
> df<-data.frame(x,y,z,stringsAsFactors = FALSE)
> df
  x y z
1 1 4 a
2 2 5 b
3 3 6 c

> str(df)
'data.frame':	3 obs. of  3 variables:
 $ x: num  1 2 3
 $ y: num  4 5 6
 $ z: chr  "a" "b" "c"
> str(x)
 num [1:3] 1 2 3
> class(x)
[1] "numeric"
> class(z)
[1] "character"
> str(df$x)
 num [1:3] 1 2 3
> class(df$x)
[1] "numeric"
> class(df)
[1] "data.frame"

> a<-matrix(c(1:12),nrow = 2, ncol = 3)
> a
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> class(a)
[1] "matrix"
> str(a)
 int [1:2, 1:3] 1 2 3 4 5 6
> b<-list(x,y,z)
> b
[[1]]
[1] 1 2 3

[[2]]
[1] 4 5 6

[[3]]
[1] "a" "b" "c"
> class(b)
[1] "list"
> str(b)
List of 3
 $ : num [1:3] 1 2 3
 $ : num [1:3] 4 5 6
 $ : chr [1:3] "a" "b" "c"

is.array, is.factor, is.data.frame, is.numeric.....등 is로 시작하는 함수는 해당타입인지 확인이 가능하다.

as.array, as.factor, as.data.frame, as.numeric...등 as로 시작하는 함수는 형변환(casting)에 사용한다.

> x<-c(1,2,3)
> is.numeric(x)
[1] TRUE
> y<-as.factor(x)
> str(x)
 num [1:3] 1 2 3
> class(x)
[1] "numeric"
> x
[1] 1 2 3
> str(y)
 Factor w/ 3 levels "1","2","3": 1 2 3
> class(y)
[1] "factor"

> x<-matrix(c(1:12),nrow = 2, ncol = 3)
> x
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> class(x)
[1] "matrix"
> str(x)
 int [1:2, 1:3] 1 2 3 4 5 6
> y<-as.data.frame(x)
> y
  V1 V2 V3
1  1  3  5
2  2  4  6
> class(y)
[1] "data.frame"
> str(y)
'data.frame':	2 obs. of  3 variables:
 $ V1: int  1 2
 $ V2: int  3 4
 $ V3: int  5 6

> z<-list(c(1,2,3),c('a','b','c'))
> z
[[1]]
[1] 1 2 3

[[2]]
[1] "a" "b" "c"

> class(z)
[1] "list"
> str(z)
List of 2
 $ : num [1:3] 1 2 3
 $ : chr [1:3] "a" "b" "c"
> aa<-as.data.frame(z)
> aa
  c.1..2..3. c..a....b....c..
1          1                a
2          2                b
3          3                c
> class(aa)
[1] "data.frame"
> str(aa)
'data.frame':	3 obs. of  2 variables:
 $ c.1..2..3.      : num  1 2 3
 $ c..a....b....c..: Factor w/ 3 levels "a","b","c": 1 2 3

 

반응형
Comments