R에서 source() 함수를 이용해서 이미 저장된 R 함수를 사용할 수 있게 한다.


그런데. R소스의 위치는 R를 로딩하고 나서야 위치를 알 수 있는 부분이 존재한다.


MacOS에서 source()함수를 잘 활용하려면, Rstudio를 Application에서 실행하는 것 대신


작업 R디렉토리(working R directory) 에서 Rstudio를 실행하는 것이 개발에 유리한 것 같다.


아래와 같이 실행하면 Rstudio가 작업 R디렉토리에서 source() 함수 호출을 쉽게 할 수 있다.


$ cd /mydev/r-workspace/log/ 

/Applications/RStudio.app/Contents/MacOS/RStudio &




Posted by '김용환'
,



transform, apply, cbind 함수를 data.frame에 사용하면 보통 list 또는 dataframe로 리턴된다.


dataFrame$newColumn <- apply(dataFrame, 1, function(x) { . . . } )



dataFrame <- transform(dataFrame, newColumnName = some equation)


data.frame를 리턴하지 않고, 특정 컬럼값만 변경하고 싶은 경우에는 다음과 같이 쉽게 쓸 수 있다. (이게 R의 매력인 것 같다.)


> dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))

> dat

  x y z

1 1 3 5

2 2 4 6


> dat$z <- dat$z * 2

> dat

  x y  z

1 1 3 10

2 2 4 12


> dat$y <- ifelse (dat$y == 4 , 0, 10)

> dat

  x  y  z

1 1 10 10

2 2  0 12






Posted by '김용환'
,



elasticsearch http api의 요청/응답을 json 라이브러리인 jsonlite를 썼더니, 이상하게 json을 꼬이게 한다. 배열(])을 더 추가하는 버그가 있다. 


동일한 코드에 대해서 rjson을 썼다니, 잘 동작한다. 헐..




install.packages("rjson")

library(rjson)


aa <- fromJSON(body)

body$x$a$b <- "test"

bb <- toJSON



Posted by '김용환'
,



R의 elasticsearch 모듈(https://github.com/ropensci/elastic)이 있으며, 설치는 아래와 같이 한다.


install.packages("elastic")


모듈 임포트는 다음과 같이 한다.


library("elastic")



현재 69가지 지원하는 api는 다음과 같다.


 ls('package:elastic')

 [1] "alias_create"          "alias_delete"         

 [3] "alias_exists"          "alias_get"            

 [5] "aliases_get"           "cat_"                 

 [7] "cat_aliases"           "cat_allocation"       

 [9] "cat_count"             "cat_fielddata"        

[11] "cat_health"            "cat_indices"          

[13] "cat_master"            "cat_nodes"            

[15] "cat_pending_tasks"     "cat_plugins"          

[17] "cat_recovery"          "cat_segments"         

[19] "cat_shards"            "cat_thread_pool"      

[21] "cluster_health"        "cluster_pending_tasks"

[23] "cluster_reroute"       "cluster_settings"     

[25] "cluster_state"         "cluster_stats"        

[27] "connect"               "connection"           

[29] "count"                 "docs_bulk"            

[31] "docs_create"           "docs_delete"          

[33] "docs_get"              "docs_mget"            

[35] "es_parse"              "explain"              

[37] "field_mapping_get"     "index_analyze"        

[39] "index_clear_cache"     "index_close"          

[41] "index_create"          "index_delete"         

[43] "index_exists"          "index_flush"          

[45] "index_get"             "index_open"           

[47] "index_optimize"        "index_recovery"       

[49] "index_segments"        "index_settings"       

[51] "index_settings_update" "index_stats"          

[53] "index_status"          "index_upgrade"        

[55] "mapping_create"        "mapping_delete"       

[57] "mapping_get"           "mlt"                  

[59] "nodes_hot_threads"     "nodes_info"           

[61] "nodes_shutdown"        "nodes_stats"          

[63] "ping"                  "scroll"               

[65] "Search"                "search_shards"        

[67] "Search_uri"            "tokenizer_set"        

[69] "type_exists"    



간단한 예제는 다음과 같다.


conn <- connect(es_base="http://abc.google.com" ,es_port=9200)


exist <- alias_exists(alias="search_autocomplete")

docs_get(index = 'search_autocomplete', type = 'read', id = 4)



질의시에는 json으로 할 수 있고,


body <- '{

 "query": {

   "query_string": {

     "query" : "backup"

   }

 }

}'

out <- Search('search_autocomplete', 'read', body=body)



list를 이용해서도 진행할 수 있다.


body <- list(query = list(query_string = list(query = "backup")))

out <- Search('search_autocomplete', 'read', body=body)



구현은 아주 간단히 http rest api를 감싼 형태를 구현하였다.

그러나, 이슈가 하나 있는데, api에서 본 것처럼 elasticsearch 연결 정보는 오직 하나만 쓸 수 있다. 

(R 모듈을 많이 쓰다보면, 같이 사용하는 전역 변수 이름 때문에 문제가 되는 경우가 있다.)

즉, 하나의 es만 써야 한다.  동시에 2개 es를 연결해서 migration 하거나 데이터를 같이 작업해야 하는 것은 할 수 없다.



* 그래서 (나는) 여러 es에서 쓸 수 있도록 해당 소스를 수정해서 개발했다. 

수정하는데 그렇게 어렵지 않아서 쉽게 쓸 수 있을 것이다. 








Posted by '김용환'
,

[R] R 소스 실행하기

R 2015. 7. 25. 12:18




R소스에서 다른 R 소스를 실행하기 위해서는 source() 함수를 실행한다.


source('/mydev/work.R', echo=TRUE)

Posted by '김용환'
,

[R] 로그 출력하기 (print)

R 2015. 7. 25. 12:16



R에서 로그 출력하는 방법은 다양하다.




> cat("Current working dir: ", "/mydev")

Current working dir:  /mydev


> paste0("Current working dir: ", "/mydev")

[1] "Current working dir: /mydev"


> print(paste0("Current working dir: ", "/mydev"))

[1] "Current working dir: /mydev"


> sprintf("Current working dir: %s", "/mydev")

[1] "Current working dir: /mydev"


> message("Current working dir: ", "/mydev")

Current working dir: /mydev

 



Posted by '김용환'
,


R에서 data frame의 길이가 length() 함수로 구하는 것 같았는데, 테스트해보니 column 개수(=ncol)를 나타난다. (java와 다르다.)

row 개수를 구하려면 nrow() 함수를 사용한다.




> set.seed(1)

> dataset <- data.frame(A = sample(c(NA, 1:100), 100, rep = TRUE),

+                       B = rnorm(100))

> length(dataset)

[1] 2

> nrow(dataset)

[1] 100

> ncol(dataset)

[1] 2






Posted by '김용환'
,



여러 컬럼으로 이루어진 data.frame의 부분 집합을 분리할 수 있다. 


아래 예제는 여러 컬럼으로 이루어진 data.frame을 as.data.frame()과 c()를 이용하여 2개의 컬럼으로 이루어진 data.frame으로 분리할 수 있다.



split_dataframe <- function(df) {
+   as.data.frame(df[,c("key", "count")])
+ }
> count_df <- split_dataframe(count_df)
> count_df
          key doc_count
1 10751028      3471
2 18581607      2008
3 10731896      1587

4 20740490      1583



Posted by '김용환'
,



리스트에 항목(element)를 추가할 때는 list(), append()를 이용한다.

특이할 점은 append() 사용시 순서를 잘 이용하면 된다.


아래 예제는 append(element, list)호출 형태로 스택처럼 추가되는 형태이다. 


> lst <- list()

> lst <- append(1, lst)

> lst <- append(2, lst)

> lst <- append(3, lst)

> lst

[[1]]

[1] 3


[[2]]

[1] 2


[[3]]

[1] 1



그렇다면, append(list, element)를 하면 순서대로 저장할 수 있다. 


> lst <- list()

> lst <- append(lst, 1)

> lst <- append(lst, 2)

> lst <- append(lst, 3)

> lst

[[1]]

[1] 1


[[2]]

[1] 2


[[3]]

[1] 3



R의 리스트에 다른 타입의 데이터를 저장할 수 있다.


> b <- list(center=c(10, 5), radius=5)

> class(b) <- "circle"

> b

$center

[1] 10  5


$radius

[1] 5


attr(,"class")

[1] "circle"


> lst <-append(lst, b)

> lst


[[1]]

[1] 1


[[2]]

[1] 2


[[3]]

[1] 3


$center

[1] 10  5


$radius

[1] 5





Posted by '김용환'
,

[R] R에서 도움말 얻기

R 2015. 7. 25. 09:31


R에서 도움말을 얻으려면, ?를 함수 앞에 붙인다.


?source

?paste


?(source)

?(paste)


또는 help()를 이용할 수도 있다.


help(source)

help(paste)



Rstudio에서는 F1 (또는 Fn + F1) 키를 누르면 도움말을 얻을 수 있다. 

Posted by '김용환'
,