R이 함수 언어임에도 불구하고, for문을 지원한다. for문을 쓰는 것보다 apply를 쓰는 게 좋다.

(list와 data frame으로 연결되는 복합 객체의 경우에는 for loop가 잘 동작되지 않는 경우가 많기도 하지만 함수 언어로서의 기능이 워낙 많아서..)



# for loop

sum_data<-0

for(i in 1:5) {

  sum_data <- sum_data + i

}

sum_data


결과

[1] 15



x <-0

for(i in 3:3) {

  x <-origin_data[i]

}

x


결과

  z

1 7

2 8

3 9




apply는 열 단위로 계산한다. 중간의 숫자 1은 열이고, 2는 행을 의미한다. 따라서 data frame에서 열,행 별로 계산을 가능하게 한다.



origin_data <- data.frame(x=c(1,2,3), y=c(4,5,6), z=c(7,8,9))



# apply-열 단위로 계산

test_data <- origin_data

apply(origin_data, 1, sum)

# 열 단위의 계산 값을 마지막 행에 추가

test_data$sum <- apply(origin_data, 1, sum)

test_data


결과

[1] 12 15 18



# apply-행 단위로 계산

test_data <- origin_data

apply(origin_data, 2, sum)


결과

  x y z sum

1 1 4 7  12

2 2 5 8  15

3 3 6 9  18



data frame의 4번째 열에 모든 행을 계산한 값을 추가할 수 있다.


# 모든 행의 합을 마지막열에 추가.

test_data[4,] <- apply(origin_data, 2, sum)

test_data


결과

  x  y  z

1 1  4  7

2 2  5  8

3 3  6  9

4 6 15 24



lapply는 list에 적합한 함수로서 list의 element를 순회하고, 함수를 실행한다.



# lapply - data frame 순회한다.

test_data <- origin_data

# data frame의 열을 기준으로 순회

lapply(test_data, sum)


결과

$x

[1] 6


$y

[1] 15


$z

[1] 24




# lapply - 리스트 항목 순회하고 리스트 항목마다 값을 만든다.

list_data <- list(a = 1:5, b = 6:10)

list_data

lapply(list_data, sum)


결과

$a

[1] 1 2 3 4 5


$b

[1]  6  7  8  9 10



함수를 직접 정의해서 추가할 수도 있다.


lapply(list_data, function(x) {

  if (is.integer(x)) sum(x)

})



결과

$a

[1] 15


$b

[1] 40



lapply는 결과값이 리스트라서 좀 불편할 수 있다. sapply가 심플한 버전이다. 

# sapply - 리스트를 순회하고 matrix 리스트를 리턴한다.lapply보다 더 보기 편하고 matrix로 관 할수 있다.

list_data <- list(a = 1:5, b = 6:10)

sapply(list_data, sum)

typeof(list_data)


결과

 a  b 

15 40 

[1] "list"



#mapply - 리스트의 열 단위로 복사


list_data1 <- list(a = 1:5, b = 6:10)

mapply(sum, list_data1$a, list_data1$b)


결과

[1]  7  9 11 13 15




• lapply(): list를 순회하고 각 엘리먼트에 함수를 적용한다. 

• sapply(): lappy와 같지만, 결과를 간단히 한다. 

• apply(): 배열에 함수를 적용한다. 

• tapply(): 벡터의 하위 집합에 함수를 적용한다. 

• mapply(): lapply의 다변수 버전이다. 



Posted by '김용환'
,

[R] if ~ else와 ifelse 사용법

R 2015. 11. 25. 15:00


R은 ifelse를 함께 써서 true, false에 대한 처리를 쉽게 처리할 수 있다. 



기존 if, else 관점의 처리 코드이다.
visit_count_from_redis <- if(is.null(visit_count_from_redis)) 0 else visit_count_from_redis

 
이를 ifelse로 변경한 코드이다.
visit_count_from_redis <- ifelse(is.null(visit_count_from_redis), 0, visit_count_from_redis) 


Posted by '김용환'
,


R언어에서 변수 선언시 _가 제일 먼저 오면 변수 선언을 할 수 없다.



> _test <- 'test'

에러: 예상하지 못한 입력입니다. in "_"



그러나 Reverse Single Quote(`)를 써야 변수 선언이 가능하다.


> `_test` <- 'test'

> print (`_test`)

[1] "test"



참고로 R 패키지중 elasticsearch와 연동하는 케이스에서는 _로 시작되는 json 부분때문에 `_source` (또는 `_id`)가 아닌 X_Source, X_id로 변경하고 있다. 




Posted by '김용환'
,


R에서 data table에서 특정 조건에 맞는 row만 포함하려는 data table만 얻으려면 아래와 같이 한다.

http://knight76.tistory.com/entry/R-data-table%EC%97%90%EC%84%9C-%ED%8A%B9%EC%A0%95-%EC%A1%B0%EA%B1%B4%EC%9D%98-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%A0%9C%EC%99%B8%ED%95%98%EA%B8%B0


그러나 R에서 data frame에 대해서는 data table처럼 하면 에러가 발생한다. 

 table[!(table$B ==0)]



data frame의 경우는 아래와 같이 사용하면 filter한 데이터만 data frame으로 재생성할 수 있다.


matched_poi = poi[poi$found == "TRUE",]


Posted by '김용환'
,



data table에서 특정 조건의 데이터를 제외하고 싶을 때 사용할 수 있는 R 스크립트이다. 


A <- c('samuel','young', 'merling', 'flynn')

B <- c(100, 0, 80, 90)

table <- data.table(A,B)

table



결과는 다음과 같다.


         A   B

1:  samuel 100

2:   young   0

3: merling  80

4:   flynn  90



아래 예제에서 특정 점수가 0점은 young의 row를 삭제하고 싶다면 다음과 같이 조건문을 써서 정리할 수 있다.


table <- table[!(table$B ==0)]

table


결과


         A   B

1:  samuel 100

2: merling  80

3:   flynn  90



 또는 아래와 같은 == 뿐 아니라 true/false의 조건문이면 가능하다.(심지어 문자열도..)


table <- table[!(table$B <= 50)]


table <- table[!(table$A == "samuel")]







Posted by '김용환'
,


list 안에 data.table(또는 data.frame)을 포함된 복합체를 파일로 저장하고 읽기를 할 수 있다. 


저장하기

save(scroll_result, file="scroll_result.rda")



읽기

  load("scroll_result.rda")



또는 

  

  attach("scroll_result.rda")



write.table() 호출시 logical, true/false 관련 에러가 날 때, 대안으로 save를 사용할 수 있다. 

Posted by '김용환'
,


github의 R 소스를 설치할 때, 다음과 같이 devtools 패키지를 설치하고, devtools::install_github를 사용한다.


install.packages("devtools")

require(devtools)

devtools::install_github('prestodb/RPresto') 
require(RPresto)



install github할 때 403 에러가 발생할 수 있다. 

> devtools::install_github('prestodb/RPresto')

Downloading GitHub repo prestodb/RPresto@master

Error in download(dest, src, auth) : client error: (403) Forbidden




403 Forbidden 에러가 발생하면,  터미널에서 테스트해서 왜 에러가 나는지 확인한다. rate limiting에 의해 403 에러가 발생하면 좀 기다리면 풀린다. 


$ curl -i https://api.github.com/repos/prestodb/RPresto

403 Forbidden

...

X-Content-Type-Options: nosniff


{

  "message": "API rate limit exceeded for 1.1.1.1. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)",

  "documentation_url": "https://developer.github.com/v3/#rate-limiting"

}





정상적일 때는 200 ok이지만, 403일 때는 body에 내용이 남겨진다.


(http://api.github.com/repos/[username]/[reponame] 포맷으로 테스트 가능)

$ curl -i https://api.github.com/repos/prestodb/RPresto

HTTP/1.1 200 OK

Server: GitHub.com

Date: Tue, 06 Oct 2015 08:23:33 GMT

Content-Type: application/json; charset=utf-8

Content-Length: 5938

Status: 200 OK

X-RateLimit-Limit: 60

X-RateLimit-Remaining: 18

X-RateLimit-Reset: 1444121790

Cache-Control: public, max-age=60, s-maxage=60

Last-Modified: Fri, 11 Sep 2015 04:44:50 GMT

ETag: "1dfc5985c248ad055c8a6ba89f0f5cf9"

Vary: Accept

X-GitHub-Media-Type: github.v3

X-XSS-Protection: 1; mode=block

X-Frame-Options: deny

Content-Security-Policy: default-src 'none'

Access-Control-Allow-Credentials: true

Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval

Access-Control-Allow-Origin: *

X-GitHub-Request-Id: D3386033:1768B:34FB0FA:56138504

Strict-Transport-Security: max-age=31536000; includeSubdomains; preload

X-Content-Type-Options: nosniff

Vary: Accept-Encoding

X-Served-By: cee4c0729c8e9147e7abcb45b9d69689


{

  "id": 32487073,

  "name": "RPresto",

  "full_name": "prestodb/RPresto",

  "owner": {

    "login": "prestodb",

    "id": 6882181,

    "avatar_url": "https://avatars.githubusercontent.com/u/6882181?v=3",

    "gravatar_id": "",

    "url": "https://api.github.com/users/prestodb",

    "html_url": "https://github.com/prestodb",

    "followers_url": "https://api.github.com/users/prestodb/followers",

    "following_url": "https://api.github.com/users/prestodb/following{/other_user}",

    "gists_url": "https://api.github.com/users/prestodb/gists{/gist_id}",

    "starred_url": "https://api.github.com/users/prestodb/starred{/owner}{/repo}",

    "subscriptions_url": "https://api.github.com/users/prestodb/subscriptions",

    "organizations_url": "https://api.github.com/users/prestodb/orgs",

    "repos_url": "https://api.github.com/users/prestodb/repos",

    "events_url": "https://api.github.com/users/prestodb/events{/privacy}",

    "received_events_url": "https://api.github.com/users/prestodb/received_events",

    "type": "Organization",

    "site_admin": false

  },

  "private": false,

  "html_url": "https://github.com/prestodb/RPresto",

  "description": "DBI-based adapter for Presto for the statistical programming language R.",

  "fork": false,

  "url": "https://api.github.com/repos/prestodb/RPresto",

  "forks_url": "https://api.github.com/repos/prestodb/RPresto/forks",

  "keys_url": "https://api.github.com/repos/prestodb/RPresto/keys{/key_id}",

  "collaborators_url": "https://api.github.com/repos/prestodb/RPresto/collaborators{/collaborator}",

  "teams_url": "https://api.github.com/repos/prestodb/RPresto/teams",

  "hooks_url": "https://api.github.com/repos/prestodb/RPresto/hooks",

  "issue_events_url": "https://api.github.com/repos/prestodb/RPresto/issues/events{/number}",

  "events_url": "https://api.github.com/repos/prestodb/RPresto/events",

  "assignees_url": "https://api.github.com/repos/prestodb/RPresto/assignees{/user}",

  "branches_url": "https://api.github.com/repos/prestodb/RPresto/branches{/branch}",

  "tags_url": "https://api.github.com/repos/prestodb/RPresto/tags",

  "blobs_url": "https://api.github.com/repos/prestodb/RPresto/git/blobs{/sha}",

  "git_tags_url": "https://api.github.com/repos/prestodb/RPresto/git/tags{/sha}",

  "git_refs_url": "https://api.github.com/repos/prestodb/RPresto/git/refs{/sha}",

  "trees_url": "https://api.github.com/repos/prestodb/RPresto/git/trees{/sha}",

  "statuses_url": "https://api.github.com/repos/prestodb/RPresto/statuses/{sha}",

  "languages_url": "https://api.github.com/repos/prestodb/RPresto/languages",

  "stargazers_url": "https://api.github.com/repos/prestodb/RPresto/stargazers",

  "contributors_url": "https://api.github.com/repos/prestodb/RPresto/contributors",

  "subscribers_url": "https://api.github.com/repos/prestodb/RPresto/subscribers",

  "subscription_url": "https://api.github.com/repos/prestodb/RPresto/subscription",

  "commits_url": "https://api.github.com/repos/prestodb/RPresto/commits{/sha}",

  "git_commits_url": "https://api.github.com/repos/prestodb/RPresto/git/commits{/sha}",

  "comments_url": "https://api.github.com/repos/prestodb/RPresto/comments{/number}",

  "issue_comment_url": "https://api.github.com/repos/prestodb/RPresto/issues/comments{/number}",

  "contents_url": "https://api.github.com/repos/prestodb/RPresto/contents/{+path}",

  "compare_url": "https://api.github.com/repos/prestodb/RPresto/compare/{base}...{head}",

  "merges_url": "https://api.github.com/repos/prestodb/RPresto/merges",

  "archive_url": "https://api.github.com/repos/prestodb/RPresto/{archive_format}{/ref}",

  "downloads_url": "https://api.github.com/repos/prestodb/RPresto/downloads",

  "issues_url": "https://api.github.com/repos/prestodb/RPresto/issues{/number}",

  "pulls_url": "https://api.github.com/repos/prestodb/RPresto/pulls{/number}",

  "milestones_url": "https://api.github.com/repos/prestodb/RPresto/milestones{/number}",

  "notifications_url": "https://api.github.com/repos/prestodb/RPresto/notifications{?since,all,participating}",

  "labels_url": "https://api.github.com/repos/prestodb/RPresto/labels{/name}",

  "releases_url": "https://api.github.com/repos/prestodb/RPresto/releases{/id}",

  "created_at": "2015-03-18T22:11:28Z",

  "updated_at": "2015-09-11T04:44:50Z",

  "pushed_at": "2015-10-02T17:48:23Z",

  "git_url": "git://github.com/prestodb/RPresto.git",

  "ssh_url": "git@github.com:prestodb/RPresto.git",

  "clone_url": "https://github.com/prestodb/RPresto.git",

  "svn_url": "https://github.com/prestodb/RPresto",

  "homepage": null,

  "size": 308,

  "stargazers_count": 26,

  "watchers_count": 26,

  "language": "R",

  "has_issues": true,

  "has_downloads": true,

  "has_wiki": true,

  "has_pages": false,

  "forks_count": 2,

  "mirror_url": null,

  "open_issues_count": 5,

  "forks": 2,

  "open_issues": 5,

  "watchers": 26,

  "default_branch": "master",

  "organization": {

    "login": "prestodb",

    "id": 6882181,

    "avatar_url": "https://avatars.githubusercontent.com/u/6882181?v=3",

    "gravatar_id": "",

    "url": "https://api.github.com/users/prestodb",

    "html_url": "https://github.com/prestodb",

    "followers_url": "https://api.github.com/users/prestodb/followers",

    "following_url": "https://api.github.com/users/prestodb/following{/other_user}",

    "gists_url": "https://api.github.com/users/prestodb/gists{/gist_id}",

    "starred_url": "https://api.github.com/users/prestodb/starred{/owner}{/repo}",

    "subscriptions_url": "https://api.github.com/users/prestodb/subscriptions",

    "organizations_url": "https://api.github.com/users/prestodb/orgs",

    "repos_url": "https://api.github.com/users/prestodb/repos",

    "events_url": "https://api.github.com/users/prestodb/events{/privacy}",

    "received_events_url": "https://api.github.com/users/prestodb/received_events",

    "type": "Organization",

    "site_admin": false

  },

  "network_count": 2,

  "subscribers_count": 20

}




Posted by '김용환'
,

[R]의 summary 의미

R 2015. 9. 10. 19:53



R에서 iris 라는 data.frame 클래스의 테스트 샘플 데이터를 제공한다. 이를 이용하서 summary의 의미를 보았다.


소스

head(iris)

summary(iris)




결과

> head(iris)

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species

1          5.1         3.5          1.4         0.2  setosa

2          4.9         3.0          1.4         0.2  setosa

3          4.7         3.2          1.3         0.2  setosa

4          4.6         3.1          1.5         0.2  setosa

5          5.0         3.6          1.4         0.2  setosa

6          5.4         3.9          1.7         0.4  setosa


> summary(iris)

  Sepal.Length    Sepal.Width     Petal.Length    Petal.Width          Species  

 Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100   setosa    :50  

 1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300   versicolor:50  

 Median :5.800   Median :3.000   Median :4.350   Median :1.300   virginica :50  

 Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199                  

 3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800                  

 Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500       



각 컬럼별로 통계를 6가지 정보를 보여준다.


1. min (최소값)

2. 1st Qu.(1사 분위수)  - 컬럼 데이터를 오름차순으로 정렬하여 아래에서부터 25% 위에 있는 값 (즉, 하위 25%의 값)을 의미한다.

3. Median (중앙값) - 컬럼 데이터를 오름차순으로 정렬하여 가운데에 있는 값을 의미한다.

4. Mean (평균값) - 평균

5. 3st Qu.(1사 분위수) - 컬럼 데이터를 오름차순으로 정렬하여 아래에서부터 75% 위에 있는 값 (즉, 상위 25%의 값)을 의미한다.

6. 최대값 (Max)




'R' 카테고리의 다른 글

[R] 복합체 파일 저장하기/읽기  (0) 2015.11.23
[R] github r 패키지 소스 설치  (0) 2015.10.06
[R]의 fix() 함수  (0) 2015.09.09
R에서 표준편차/평균 구하기  (0) 2015.09.09
[R] rbind와 cbind 예제  (0) 2015.09.03
Posted by '김용환'
,

[R]의 fix() 함수

R 2015. 9. 9. 17:37


R에서 fix() 함수는 기본(내가 정의한 함수도 포함) 함수를 변경할 수 있도록 한다. 

R 터미널에서 사용하니, vi 창으로 이동 후, 저장한 대로 쓸 수 있게 한다.




실제 테스트 코드


> f <- function(a, b) {

+ a + b

+ }

> f(1,1)

[1] 2

> fix(f)

> fix(f)

> f

function(a, b) {

a + b +1

}

> f(1,1)

[1] 3

>


참고로 RStudio에서도 쓸 수 있다.


'R' 카테고리의 다른 글

[R] github r 패키지 소스 설치  (0) 2015.10.06
[R]의 summary 의미  (0) 2015.09.10
R에서 표준편차/평균 구하기  (0) 2015.09.09
[R] rbind와 cbind 예제  (0) 2015.09.03
[R] NULL과 NA 비교  (0) 2015.09.01
Posted by '김용환'
,



표준편차와 평균을 구하는 함수이다. mean,sd(표준편차를 영어의 앞자만 묶음)로 쉽게 구할 수 있다.






mean(c(1, 2, 3, 4))

sd(c(1, 2, 3, 4))


simpleStats <- function(x) {

  n <- length(x)

  sampleMean <- sum(x) / n

  sampleSD <- sqrt(sum((x-sampleMean)^2) / (n-1))

  return (list("sampleMean"=sampleMean, "sampleSD" = sampleSD))

}


simpleStats(c(1,2,3,4))




결과

> mean(c(1, 2, 3, 4))
[1] 2.5
> sd(c(1, 2, 3, 4))
[1] 1.290994
> simpleStats <- function(x) {
+ n <- length(x)
+ sampleMean <- sum(x) / n
+ sampleSD <- sqrt(sum((x-sampleMean)^2) / (n-1))
+ return (list("sampleMean"=sampleMean, "sampleSD" = sampleSD))
+ }
> simpleStats(c(1,2,3,4))
$sampleMean
[1] 2.5

$sampleSD
[1] 1.290994



참고로 분산은 var() 함수로 구할 수 있다. 
> var(c(1,2,3,4))
[1] 1.666667


'R' 카테고리의 다른 글

[R]의 summary 의미  (0) 2015.09.10
[R]의 fix() 함수  (0) 2015.09.09
[R] rbind와 cbind 예제  (0) 2015.09.03
[R] NULL과 NA 비교  (0) 2015.09.01
[R] matrix에서 column, row 이름 변경하기  (0) 2015.09.01
Posted by '김용환'
,