data frame을 data table로 그냥 변환하면 이상한 값이 나온다. 

row name 때문에 발생하기 때문에, 이 부분을 옵션으로 넣으면 문제 없이 잘 동작한다.

해당 옵션은 keep.rownames=TRUE 또는 rownames() 함수이다.



소스


library("data.table")


new_df

dt <- as.data.frame.table(new_df)

dt


data.table(new_df, keep.rownames=TRUE)


data.table(name=rownames(new_df),new_df)






결과 



> library("data.table")

> new_df

        mt na sa

samuel  90 90 80

aston   90 90 80

patrick 80 60 90

> dt <- as.data.frame.table(new_df)

> dt

     Var1 Var2 Freq.mt Freq.na Freq.sa

1  samuel   mt      90      90      80

2   aston   mt      90      90      80

3 patrick   mt      80      60      90

4  samuel   na      90      90      80

5   aston   na      90      90      80

6 patrick   na      80      60      90

7  samuel   sa      90      90      80

8   aston   sa      90      90      80

9 patrick   sa      80      60      90

> data.table(new_df,keep.rownames=TRUE)

        rn mt na sa

1:  samuel 90 90 80

2:   aston 90 90 80

3: patrick 80 60 90

> dt <- data.table(name=rownames(new_df),new_df)

      name mt na sa

1:  samuel 90 90 80

2:   aston 90 90 80

3: patrick 80 60 90


Posted by 김용환 '김용환'

댓글을 달아 주세요



R에서 배열로 data frame 만들고, 특정 컬럼 삭제하는 예제이다. 


배열의 값을 data.frame을 만드는 것은 그리 어렵지 않으나, 특정 컬럼을 삭제하기 위해서는 좀 신경써야 한다. 



nm = c("samuel", "aston", "patrick") 

mt = c(80, 90, 80) 

na = c(100, 90, 80)

sa = c(80, 80, 90)

df = data.frame(nm, mt, na, sa) 

row.names(df) <- df$nm

df


drops <- c("nm")

df <- df[,!(names(df) %in% drops)]

df







결과


> nm = c("samuel", "aston", "patrick")

> mt = c(80, 90, 80)

> na = c(100, 90, 80)

> sa = c(80, 80, 90)

> df = data.frame(nm, mt, na, sa)

> drops <- c("nm")

> row.names(df) <- df$nm

> df

             nm mt  na sa

samuel   samuel 80 100 80

aston     aston 90  90 80

patrick patrick 80  80 90

> df <- df[,!(names(df) %in% drops)]

> df

        mt  na sa

samuel  80 100 80

aston   90  90 80

patrick 80  80 90





Posted by 김용환 '김용환'

댓글을 달아 주세요



여러 list의 column 값을 하나의 data frame으로 만들 수 있다. (combine)



m1 <- c(260, 300, 250, 280, 310)

m2 <- c(180, 200, 210, 190, 170)

m3 <- c(210, 250, 260, 210, 220)


df <-data.frame("moo1"=m1, "moo2"=m2, "moo3"=m3)

df



결과

  moo1 moo2 moo3
1  260  180  210
2  300  200  250
3  250  210  260
4  280  190  210
5  310  170  220


Posted by 김용환 '김용환'

댓글을 달아 주세요

[R] 함수 재정의 및 해제

R 2015. 8. 20. 10:48



R에서 함수를 재정의를 할 수 있으며, 기존의 base 함수도 재정의 가능하다.

재정의한 함수를 rm() 함수를 이용하여 원복할 수 있는 기능도 제공한다. 

해당 사례를 예제로 표현하였다.


paste("11", "22")

paste <- function(..., sep="") {

  paste0(...)

}

paste("11", "22")


rm(paste)


paste("11", "22")





R 실행 결과이다.  paste 함수가 paste0과 동일하게 작동함을 볼 수 있고, rm() 함수 호출 이후에는 다시 원래대로 동작되었다.

> paste("11", "22")
[1] "11 22"
> paste <- function(..., sep="") {
+ paste0(...)
+ }
> paste("11", "22")
[1] "1122"
> rm(paste)
> paste("11", "22")
[1] "11 22"



Posted by 김용환 '김용환'

댓글을 달아 주세요


R에서 세로 열 문자열을 한 줄로 된 문자열로 변경하는 예이다. 

scan, paste0을 이용하면 쉽게 바꿀 수 있다. 


category.txt 에 다음 내용의 파일이 존재한다.


airport

amusement_park

aquarium

art_gallery

bakery

bar

,,,



소스

scanned <- scan("category.txt", what="")

pasted <- paste0("\"", paste0(scanned, collapse="\",\""), "\"")

writeLines(text=pasted, "cc.txt")


결과 (cc.txt)


"airport","amusement_park","aquarium","art_gallery","bakery","bar",...


Posted by 김용환 '김용환'

댓글을 달아 주세요

[R] par() 함수

R 2015. 8. 12. 21:08



par() 함수는 그래프를 그릴 때 파라미터를 줄 수 있다.


par(new=T) 는 그래프를 겹쳐 그린다는 것이다.


par(family="AppleGothic") 는 그림 그릴 때 한글이 깨질 때 폰트를 설정한다. 


Posted by 김용환 '김용환'

댓글을 달아 주세요




RStudio 에서 특정 디렉토리에서 작업하고 싶을 때 다음과 같이 사용가능하다.



1. 홈 디렉토리로 이동 후 RStudio를 실행한다.


[리눅스]

cd /mydev/workspace && Rscript test.R


[맥]

cd /mydev/workspace &&  /Applications/RStudio.app/Contents/MacOS/RStudio &



2. Rstudio 코드에서 setwd를 이용한다.


setwd("/mydev/workspace")


Posted by 김용환 '김용환'

댓글을 달아 주세요



RStudio에서 모든 변수에 설정된 값을 초기화하려면 RStudio의 오른쪽 창의 Environment의 청소 아이콘을 선택한다.

아니면, Session -> Clear Workspace를 선택한다.





R 터미널에서는  rm(list=ls()) 를 실행하면 메모리를 청소한다. 



> a <- c(1,2)

> ls()

[1] "a"

> list <- ls()

> list

[1] "a"

> a <- c(1,2)

> list <- ls()

> list

[1] "a"

> rm(list=ls())

> a

에러: 객체 'a'를 찾을 수 없습니다


여기에 gc()를 해주면 깔끔히 데이터를 정리한다. 



> a<-"111"

> b<-"222"

> rm(list = ls())

> gc()

         used (Mb) gc trigger (Mb) max used (Mb)

Ncells 427431 22.9     750400 40.1   592000 31.7

Vcells 652770  5.0    1723292 13.2  1622949 12.4

> a

에러: 객체 'a'를 찾을 수 없습니다



'R' 카테고리의 다른 글

[R] par() 함수  (0) 2015.08.12
[R] RStudio를 특정 디렉토리에서 작업하기  (0) 2015.08.12
[R] R에서 메모리 정리하기  (0) 2015.08.12
[R] stop() 함수와 에러 처리 방법  (0) 2015.08.11
[R] List Iterator  (0) 2015.08.06
R 의 함수 aliasing (별명)  (0) 2015.08.06
Posted by 김용환 '김용환'

댓글을 달아 주세요



R에서 함수에서 에러를 내고 멈추는 함수인 stop()이 있다. 

https://stat.ethz.ch/R-manual/R-devel/library/base/html/stop.html



해당 함수의 실제 용법을 본다.



httr 모듈을 사용한 R elasticsearch client (search_POST)를 살펴본다. 

202 이상의 Http 상태 값을 가지면 stop() 함수가 호출된다. 


https://github.com/ropensci/elastic/blob/2e3a72e42f14d73560a5367195cc2461acc32975/R/search.r

search_POST <- function(path, index=NULL, type=NULL, args, body, raw, asdf, ...) {

  checkconn()

  conn <- es_get_auth()

  url <- make_url(conn)

  if (is.null(index) && is.null(type)) {

    url <- paste(url, path, sep = "/")

  } else {

    if (is.null(type) && !is.null(index)) {

      url <- paste(url, index, path, sep = "/")

    } else {

      url <- paste(url, index, type, path, sep = "/")

    }

  }

  url <- prune_trailing_slash(url)

  body <- check_inputs(body)

  tt <- POST(url, make_up(), ..., query = args, body = body)

  if (tt$status_code > 202) stop(error_parser(tt, 1), call. = FALSE)

  res <- content(tt, as = "text")

  if (raw) res else jsonlite::fromJSON(res, asdf)

}





만약 stop()함수 결과를 처리하려면 어떻게 할지에 대한 결과처리는 다음과 같다. 

stop() 함수 결과는 에러 메시지는 character 타입을 가지고 있으며 "try-error" 클래스 이다. 이에 맞는 처리를 해주면 정상처리할 수 있다. 아래 코드는 while 루프에서 루프를 나갈 수 있는 조건으로 활용하고 있다. 



while(true) {

..

scroll_result <- try(search_POST(url = conn$baseurl, path = "_search/scroll?scroll=10m", body = scroll_id))

if (typeof(scroll_result) == "character" && class(scroll_result) == "try-error") {
    break;

}
..
}




Posted by 김용환 '김용환'

댓글을 달아 주세요

[R] List Iterator

R 2015. 8. 6. 21:46


R의 List의 값을 Iteration하고 싶을 때, 사용할 수 있는 코드이다.



첫번째 예제이다. 단순히 for each를 이용하는 예제이다.


mylist <- list(x <- 1:10)

mylist


for (x in mylist) {

  print(x)

}



결과는 다음과 같다.

> mylist
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10


> for (x in mylist) {
+   print(x)
+ }
 [1]  1  2  3  4  5  6  7  8  9 10



두번째 예제는 iterators 라이브러리를 로딩한 경우이다. nextElem이 마지막 원소의 다음을 가르키게 되면 에러가 발생하는데, 이를 try문으로 예외를 잡게 하고 try-error인 class인 경우에는 loop를 빠지게 하는 코드이다. 
(try 문이 의외로 중요한 상황에서 쓰일 수 있은 잘 기억한다!!)


library(iterators)

it <- iter(mylist)
while (TRUE) {
  d = try(nextElem(it))
  if (class(d) == "try-error") break
  print(d)
}

결과는 다음과 같다.


> library(iterators)
> it <- iter(mylist)
> while (TRUE) {
+   d = try(nextElem(it))
+   if (class(d) == "try-error") break
+   print(d)
+ }
 [1]  1  2  3  4  5  6  7  8  9 10
Error : StopIteration




'R' 카테고리의 다른 글

[R] R에서 메모리 정리하기  (0) 2015.08.12
[R] stop() 함수와 에러 처리 방법  (0) 2015.08.11
[R] List Iterator  (0) 2015.08.06
R 의 함수 aliasing (별명)  (0) 2015.08.06
[R] rjson으로 data frame 으로 만들기  (0) 2015.08.05
[R] 리눅스 (Red-hat 계열) 모듈 설치  (0) 2015.08.05
Posted by 김용환 '김용환'

댓글을 달아 주세요