R로 트래픽과 관련된 시뮬레이션 작업을 하면서 필요했던 부분에 대해 기록했다.
기본
사칙 연산
1 2 3 4 5 6 7 |
1+1 # 2 1-1 # 0 1*2 # 2 2/1 # 2 # 나머지 3%%2 # 1 |
NULL 체크
R에서는 is를 사용해서 타입을 체크할 수 있다.
1 2 3 4 5 6 7 8 9 |
foo = NA bar = 'bar' if(is.na(foo)) { print('foo is null.') } if(!is.na(bar)) { print('bar is not null.') } |
포맷에 맞춰서 출력하기
C에서 printf와 유사하게 R에서도 포맷에 맞춰 출력할 수 있다.
1 2 3 4 5 6 7 8 9 10 11 |
A = 'A' B = 'B' C = 'C' print( sprintf( "OUTPUT : %s, %s, %s", A, B, C ) ) [1] "OUTPUT : A, B, C" |
변수 타입 알아내기
어떤 변수의 타입을 알아낼 때 필요한 함수들이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# class class(mtcars) [1] "data.frame" # str str(mtcars) 'data.frame': 32 obs. of 11 variables: $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ... $ cyl : num 6 6 4 6 8 6 8 4 4 6 ... $ disp: num 160 160 108 258 360 ... $ hp : num 110 110 93 110 175 105 245 62 95 123 ... $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ... $ wt : num 2.62 2.88 2.32 3.21 3.44 ... $ qsec: num 16.5 17 18.6 19.4 17 ... $ vs : num 0 0 1 1 0 1 0 1 1 1 ... $ am : num 1 1 1 0 0 0 0 0 0 0 ... $ gear: num 4 4 4 3 3 3 3 4 4 4 ... $ carb: num 4 4 1 1 2 1 4 2 2 4 ... |
vector의 인덱스 구하는 방법
1 |
idx = match(key, temp_list$key) |
반복(Loop)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# for 루프 for(mpg in mtcars$mpg) { print(mpg) } # while 루프 i = 1 total = length(mtcars$mpg) while(TRUE) { if(total < i) { break } print(mtcars$mpg[i]) i = i + 1 } |
2개의 vector에서 교집합 구하기
1 2 3 |
a = c("A", "B", "C", "D", "E") b = c("1", "2", "3", "4", "E") intersect(a, b) # E |
파일
현재 소스파일 경로 구하기
php 의 __FILE__와 같이 소스파일의 경로를 R에서도 구할 수 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
filepath = (function() { return(attr( body( sys.function() ), "srcfile" )$filename) })() print(filepath) # c:/temp/test.txt # 디렉토리도 구할 수 있다. dirname(file.path(filepath)) # 현재 작업 디렉토리 getwd() # "C:/Users/.../Documents" |
데이터 객체를 텍스트 파일로 저장하기
1 2 3 4 5 |
# 단순 텍스트로 저장. 이어서 쓰기 가능 write.table(mtcars, "C:/temp/test.txt", append = TRUE) # csv로 저장 write.csv(mtcars, "C:/temp/test.csv") |
source 불러오기 할 때 에러 해결
윈도에서 R 파일을 불러오는데 이런 에러가 발생했다. 소스에 한글이 있어서 발생했다.
1 2 3 4 5 |
> source("D:\\test.R") 경고메시지(들): In grepl("\n", lines, fixed = TRUE) : 이 로케일에서는 입력문자열 17는 유효하지 않습니다 > |
source에 함수에서 encoding 옵션을 사용해서 해결했다.
1 |
source("D:\\test.R", encoding="utf-8") |
성능
처리시간 출력하기
어떤 함수가 얼마나 걸리는지 알아볼 수 있다.
1 2 3 4 5 6 |
print(system.time( main() )) 사용자 시스템 elapsed 1.15 0.00 1.15 |
차트
plot 차트 그리기
1 2 3 4 5 6 |
plot(mtcars$mpg,mtcars$threshold, type="l", col=cols[1], lty = "dashed", xlab="seq", ylab="values", ylim=ylim, main="threshold와 다른 변수들간의 상관관계", sub=sprintf("최대 허용량 : %s, 초당 요청자수 : %s", MAX_CNT, REQUEST_CNT_PER_SEC), panel.first = grid() ) |