조조하사의 Gaming Nexus☆

[180129 R Programming] 3. Libraries, Helps, and the Faked Dices



< 이번 시작은 GUI로부터! >
This time, we start from GUI!



x에 -1부터 1까지 0.2 간격으로 나열된 수열을 주고, y에 x$^3$의 값을 준 뒤 x, y의 관계를 알려주는 그래프를 그린 모습.

I gave a sequence from -1 to 1 by 0.2 to x, x$^3$ to y and plotted.



< 점이 너무 적어서 다시 한 번?! >
Because there was so few points!?



이번엔 x에 수열을 주는데 -1부터 1까지, 항이 100개가 되도록 주었습니다.
참고로 이 때까진 y가 이전 사진에서와 같이 항이 10개뿐인 수열로 저장되어 있으므로, y<-x$^3$을 한 번 더 입력해줘야 함. 안 그러면 오류나더라구요 ㅎ


In this case, I gave to x a sequence from -1 to 1 with its length 100.
But for now, y has its length 10. So I wrote y<-x$^3$ again. If you didn't, then you'll see an error.



< 이번엔 수열을 주고 막대그래프를 그려보았습니다. >
I input lists and then plotted bar graphs.



사실 이 세 그래프 말고도 의미있는 그래프를 여럿 그려봤었는데, 일일이 찍지는 못했슴다 ㅠㅠ
왜냐하면 여기다가 의문으로 남겨놓을거기 때문에..!

의문점) 막대그래프의 넓이를 1로 {0.5, 1.5, 2.5, 3.5}의 막대그래프를 그릴 경우 0.5와 1.5는 1로, 2.5는 2로, 3.5는 3으로 편입되어 그래프가 산출됨.
왜 0.5는 0에 들어가지 않는지 생각해볼 것!
- 실험을 통한 짐작 : 수열의 첫 항이 0.5이므로 각 막대가 포함하는 범위가 [0.5, 1.5], (1.5, 2.5], (2.5, 3.5]와 같이 계산되는 듯하다!
- 가설 : 수열의 첫 항이 0.4이면, [0.4, 0.5], (0.5, 1.5], (1.5, 2.5], $\cdots$ 와 같은 식으로 계급이 정해질 것!


Actually, I plotted more graphs except above 3 bar graphs. But I didn't take shots about them.
But I'll leave here a question mark about it instead.

Question) If we plot a sequence {0.5, 1.5, 2.5, 3.5} with binwidth=1, then 0.5 and 1.5 will be put in 1, only 2.5 will be put in 2, and 3.5 will be put in 3. Why is 0.5 put in 1 instead of 0?
- Expecting by some experiments above : Since the first term of sequence is 0.5, all number in [0.5, 1.5], (1.5, 2.5], (2.5, 3.5] will be put in 1, 2, 3 respectively.
- Hypothesis : If the sequence starts from 0.4, then [0.4, 0.5], (0.5, 1.5], (1.5, 2.5], $\cdots$ are ranks of the bar graph.


*** R studio Ver. 1.1.414 기준



< 자아... 이제 TRPG러들을 골려볼까! ...근데 어? >
Now it's time to kidding TRPG players! ...but wat



주사위 dice에는 1부터 6까지의 정수열이 입력되어 있는 상황입니다.
제가 함수를 정의할 때마다 입력함수만 집어넣어서 출력이 안되게 하는군요 = =
일단 이전에도 보였던 roll() 함수(두 주사위에서 나온 눈과 그 합을 동시에 출력)를 만들어놓고,
그 밑에서 rol()이라는 새 함수를 정의하려고 해보았습니다. 책 안 보고요.

목표는 D6 2개를 굴려서 두 눈의 합을 계산하는 과정을 100회 반복, 그리고 그 결과를 막대그래프로 표현하는 것이었습니다.
......만, 보기좋게 실패했습니다.


In above shot, dice has its value already; 1:6(or, seq(1, 6, by=1))
I seem have a problem to define a function. I'm not used to writing output of the function.
Then I recalled roll() function that shows us two D6 results and their sum, and I tried to define a new function rol().

Objective : Repeat an experiment that makes sum of two D6 results 100 times, and plot it.
Of course, I failed at first.



< '?replicate'를 입력하여 도움을 요청했다! >
I put '?replicated' and called help!



효과는 뛰어났나?

a가 숫자 하나가 아닌 수열형 객체라 replicate()에 집어넣는 과정에서 에러가 일어났다고 생각해 그 부분을 고치고 돌렸슴당
이제야 막대그래프가 뜨기 시작했고, 문제가 해결된 것처럼...그런 일은 일어나지 않았습니다. 완벽한 직사각형 그 자체가 마음껏 직선미를 뽐내고 있었...
내가 잘못 쓰고 있나 싶어서 replicate()에 대한 도움말을 한 번 보았더랬죠.

위 스샷 오른쪽 도움말 페이지의 맨 아랫줄에 있는 replicate를 보고, 쓰는 순서가 잘못 되어있다는 걸 알았어요 ㅎ 으앙
그래서 밑줄친 아래쪽과 같이 함수를 수정했습니다.


하지만... 수정 뒤에 생긴 막대그래프는 여전히 균등분포를 암시하는 직사각형만을 보여주고 있었어요. 4번이나 시도했습니다!
시도하면서 변화를 보았는데, 뭔가 이상하더라구요. 계급이 1개뿐이었습니다. 무슨 일이 일어난 걸까요?


It's super effective?

I thought 'a sequence a' have occurred an error and debugged. And now I got a bar graph!
But...there is a problem remained. The bar graph showed me an perfect rectangle. So I decided to see an help for replicate() function.

In above shot, right side is the help window. I found the last sentence in the shot shows how replicate() is functional and I've been using its arguments reversed.


But after I fixed it, bar graph also plotted a rectangle even though I tried 4 times. with comparing the results...
I found an abnormal thing. Why does it have only 1 rank? What was occurred for it?



< 문제는 해결했으나... 오류를 분석해봅시다. >
Even if I solved the problem, but let me analyze the error.



결론부터 말하면, 문제는 잘 해결되었어요. 다만 해결 과정을 찍으면서 넘어가질 못했죠. 그래서 이 곳의 여백을 빌려 설명할게요!
먼저 rol()함수의 a 객체는 두 주사위를 굴려 얻은 합이고, b 객체는 그 실행을 100번 하여 결과를 저장할 예정이었지만...
a 객체가 먼저 정해지고, b 객체는 이미 정해진 a의 값을 100번 반복 입력할 뿐이었습니다. 그래서 문제가 생겼죠.


In conclusion, the problem solved. But I passed without any screenshot. So I'll explain about it here.
At the planning phase, sum of two D6 results will be saved at a, and b will save all results of 100-times repeating dice roll.
But b saved only 'fixed a' for 100 times, and the error occurred.



<굳이 함수를 쓸 필요가 없었다. 굳굳이었다.>
I didn't need any function. lol



결국, x에 두 주사위의 합을 10000번 구해서 집어넣고선 그대로 막대그래프를 만들어버렸고, 함수같은 건 필요 없었음. 후후
굳이 만들어야 할 필요가 있다면, 주사위와 반복 횟수를 달리 하고 싶을 때 정도일까.


In the result, I put replicate() function into x directly. And everything is well-done.
If we have some reasons to use a function, maybe it will be the kind of dice, and the number of repeating.



< ?과 ??의 쓰임새를 알아봅시다. 사진 오른쪽은 ??probability로 불러온 검색 목록. >
Let's learn how to use ? and ??. Lower right corner is the list called by ??probability.



?은 앞에서 봤듯 뒤에 입력된 키워드 자체의 도움말을,
??은 뒤에 입력된 키워드와 관계된 모든 종류의 도움말을 검색해주네요. 책에는 '도움말을 위한 도움말'이라 적혀있더라는..
도움말을 위한 검색기라는 표현이 더 나을지도?


As you see before, ? calls an help about the keyword.
?? calls a list of all helps in R about the keyword. In the book, it is called 'helps for help'.
Instead of it, search tool for help?



< 조작된 주사위, 그리고 1부의 마지막 사진! >
the Faked Dices, and the last shot of Project I !!



이제 y라는 객체에 sample() 함수의 새로운 인수 '확률'을 사용하여 조작된 주사위를 만들어 보았습니다!
(책에서) 도움말을 찾아본 결과, sample() 함수의 인수로는 임의 표본을 뽑을 수열, 추출 횟수, 복원 여부, 확률이 있는데, 확률로 이루어진 수열을 기입함으로써 수열의 각 항을 뽑을 확률을 지정할 수 있었지요...돌아라, 주사위!!

그리고 그는, 12가 나올 확률이 6이 나올 확률보다 높은데서 놀랍고 신기해했다고 전해진다.

그리고 드디어 총 2장에 해당하는, 프로젝트 1: 조작된 주사위의 모든 내용이 끝났습니다.(사실 2장까지 책 자체는 매우 짧습니다.)


I made a faked dice by putting a new argument of sample() function, Probability.
In help, sample() uses 4 arguments: sequence, number of sampling, replacement, probability.
We can make a faked dice with using the probability argument by putting a probability sequence in it. Rolling Dice!
and he was frightened by (probability of 12) $>$ (probability of 6)

So I finished all of Project I: the Faked Dices, which consists of Stage 1 and 2. (It's quite short ;) )



이외에 끄적끄적 해둘 만한 건 다음과 같습니다.

라이브러리 - stringi : 문자열의 사용에 관한 함수들이 모여 있음 <- 앞 포스팅의 미션 '문장 합치기'에 사용. 뒷글 참조
라이브러리 - ggplot2 : 수리통계적으로 활용가능한 GUI를 지원함
라이브러리 - lubridate : 해들리 워크햄이 책 앞쪽의 '추천의 글'에서 추천한, '날짜나 시간'을 다루는데 유용한 패키지


I make a memo here :

Library - stringi : helpful to use string operation <- I used this to solve the 'mission' which was in previous post.
Library - ggplot2 : it makes us plotting for math&statistics. supports GUI
Library - lubridate : Hadlley Wickham wrote this 'a useful tools to deal with date / time.' in recommendation of the book.