> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/ko/more-topics/29-knitr.md).

# Knitr

위키백과에 언급되어 있듯이, [Knitr는 R을 사용한 동적 보고서 생성을 위한 엔진입니다](https://en.wikipedia.org/wiki/Knitr), 통계 지향 프로그래밍 언어입니다. 이 글에서는 동적 출력을 생성하기 위해 LaTeX 문서에 R 코드를 추가하는 방법을 설명합니다.

표준 LaTeX 배포판에서는 운영 체제에 R을 설정하고, 이를 컴파일하기 위해 몇 가지 특별한 명령을 실행해야 합니다. Overleaf는 그런 번거로움을 덜어줄 수 있습니다, **knitr** 별도 설정 없이 바로 작동합니다.

## 소개

R 코드를 포함하는 문서는 다음 확장자로 저장해야 합니다 `.Rtex` 또는 `.Rnw`, 그렇지 않으면 코드가 작동하지 않습니다. 예를 살펴보겠습니다:

```latex
\documentclass{article}
\begin{document}

LaTeX{} 문서에 R 명령을 입력하면 처리되어 그 출력이 문서에 포함됩니다:

<<>>=
# 숫자 시퀀스 생성
X = 2:10

# 기본 통계 지표 표시
summary(X)

@
\end{document}
```

![KnitrDemo1.png](/files/d9ce4cb7bf0ce7487a95d333ca68baafef20189e)

&#x20;[이 예제를 `knitr` Overleaf의 예제](https://www.overleaf.com/project/new/template/20421?id=69881107\&templateName=Knitr+demo+1\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

보시다시피, 문자 사이의 텍스트 `<<>>=` 및 `@` 는 R 코드입니다. 이 코드와 그 출력은 목록 형식으로 출력됩니다. 이 코드 청크는 동적 출력을 사용자 지정하기 위해 몇 가지 추가 매개변수를 사용할 수 있습니다. 다음 섹션을 보십시오.

## 코드 청크

이전 섹션에서 제시한 것과 같은 코드 블록은 보통 *청크*라고 부릅니다. knitr 청크에서는 몇 가지 추가 옵션을 설정할 수 있습니다. 아래 예를 보십시오:

```latex
\documentclass{article}
\begin{document}

LaTeX{} 문서에 R 명령을 입력하면 처리되어 그 출력이 문서에 포함됩니다:

<<echo=FALSE, cache=TRUE>>=
# 숫자 시퀀스 생성
X = 2:10

# 기본 통계 지표 표시
summary(X)

@
\end{document}
```

![KnitrDemo2.png](/files/3385ac207bcadcab81d90504b1351b7a846166ac)

&#x20;[이 예제를 `knitr` Overleaf의 예제](https://www.overleaf.com/project/new/template/20423?id=69885763\&templateName=Knitr+demo+2\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

내부에 전달되는 추가 옵션이 세 가지 있습니다 `<<` 및 `>>`.

**echo=FALSE**

이것은 코드를 숨기고 R이 생성한 출력만 표시합니다.

**cache=TRUE**

cache를 true로 설정하면 청크는 실행되지 않고, 그 청크가 생성한 객체만 사용됩니다. 해당 청크의 데이터가 변경되지 않았다면 시간을 절약할 수 있습니다. cache=TRUE 옵션은 현재 Overleaf에서 지원되지 않지만, 로컬에서는 작동해야 합니다.

다음을 참조하세요 [참조 안내서](#reference-guide) 추가 옵션은

## 인라인 명령

청크에서 생성된 객체에 접근하여 인라인으로 출력할 수 있습니다.

```latex
\documentclass{article}
\begin{document}

LaTeX{} 문서에 R 명령을 입력하면 처리되어 그 출력이 문서에 포함됩니다:

<<echo=FALSE, cache=TRUE>>=
# 숫자 시퀀스 생성
X = 2:10

# 기본 통계 지표 표시
summary(X)

@

따라서 데이터의 평균은 $\Sexpr{mean(X)}$입니다
\end{document}
```

![KnitrDemo3.png](/files/3f2e829baf2364c45a5f675e18f3c9e4e6849ce5)

&#x20;[이 예제를 `knitr` Overleaf의 예제](https://www.overleaf.com/project/new/template/20425?id=69886866\&templateName=Knitr+demo+3\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

명령은 `\Sexpr{mean(X)}` R 코드가 반환한 출력을 출력합니다 `mean(X)`입니다. 중괄호 안에는 어떤 R 명령이든 넣을 수 있습니다.

## 플롯

플롯도 **knitr** 문서에 추가할 수 있습니다. 다음 예를 보십시오

```latex
\documentclass{article}
\begin{document}

<<plot1, fig.pos="t", fig.height=4, fig.width=4, fig.cap="First plot">>=

xdata = read.csv(file="data.txt", head=TRUE,sep=" ")

hist(xdata$data, main="Overleaf histogram", xlab="Data")

@

그림 \ref{fig:plot1}은 단순한 히스토그램입니다.

\end{document}
```

![KnitrDemo4.png](/files/2288fefb13185b8972f93f06e2da92f8214f418a)

&#x20;[이 예제를 `knitr` Overleaf의 예제](https://www.overleaf.com/project/new/template/20427?id=69890965\&templateName=Knitr+demo+3\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

이 히스토그램은 현재 작업 디렉터리에 저장된 "data.txt"에 저장된 데이터를 사용합니다. 그림과 관련된 몇 가지 옵션이 청크에 전달됩니다.

**plot1**

이것은 플롯을 참조하는 데 사용되는 레이블입니다. 접두사 "fig:"는 필수입니다. 예에서 그림이 \ref{fig:plot1}로 참조되는 것을 볼 수 있습니다.

**fig.pos="t"**

위치 지정 매개변수입니다. 그림 환경에서 사용하는 것과 동일합니다.

**fig.height=4, fig.width=4**

그림의 너비와 높이.

**fig.cap="First plot"**

그림 설명.

## 외부 R 스크립트

외부 R 스크립트의 일부를 **knitr** 문서에 가져올 수 있습니다. 스크립트를 문서에 포함하기 전에 외부 프로그램에서 작성하고 디버깅하는 것이 꽤 일반적이므로 매우 유용합니다.

다음과 같은 R 코드가 들어 있는 파일이 있다고 가정해 보겠습니다 `mycode.R` 이를 LaTeX 문서에 포함합니다:

```latex
## ---- myrcode1
# 숫자 시퀀스 생성
 X = 2:10

## ---- myrcode2
# 기본 통계 지표 표시
summary(X)
```

다음 줄에 주목하십시오

```latex
## ---- myrcode1
```

및

```latex
## ---- myrcode2
```

이 줄들은 코드 청크의 시작을 표시하며, 아래 코드 조각에서 보이듯 이 스크립트를 문서에서 사용하려면 반드시 필요합니다:

```latex
아래 청크는 출력되지 않습니다

<<echo=FALSE, cache=FALSE>>=
read_chunk("mycode.R")
@

코드는 여기 나타나야 합니다

<<myrcode2>>=

@
```

![KnitrDemo5.png](/files/8da9c61b96c477ba19b478803168ed657a952f77)

첫 번째 청크는 출력되지 않으며, 명령을 사용해 스크립트를 가져오는 데만 사용됩니다 `read_chunk("mycode.R")`, 그래서 옵션 `echo=FALSE` 이 설정되어 있습니다. 또한 스크립트는 캐시되면 안 됩니다. 스크립트가 가져와지면, 다음 뒤에 설정한 레이블을 사용하여 청크를 출력할 수 있습니다 `## ----`. 이 경우에는 `myrcode2`.

우리는 이 글의 모든 코드 조각을 다음 프로젝트에 넣었습니다  [Overleaf에서 열 수 있는](https://www.overleaf.com/project/new/template/20429?id=69894649\&templateName=Knitr+full+demo\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) .

## 참조 안내서

**몇 가지 청크 옵션**

* `결과`. R 코드가 생성한 결과의 동작을 변경합니다. 가능한 값은
  * `마크업` 출력 형식에 LaTeX를 사용합니다.
  * `asis` R의 원시 결과를 출력합니다.
  * `hold` 출력 결과를 보관했다가 청크의 끝에서 한꺼번에 내보냅니다.
  * `숨기기` 결과를 숨깁니다.
* `echo`. R 소스 코드를 포함할지 여부입니다. 다른 매개변수도 사용할 수 있습니다. `echo=2:3` 두 번째와 세 번째 줄만 출력합니다; `echo=-2:-3` 두 번째와 세 번째 줄만 제외합니다.
* `cache`. 코드 청크를 캐시할지 여부입니다. 가능한 값은 `TRUE` 및 `FALSE`
* `highlight`. 소스 코드를 강조 표시할지 여부입니다. 가능한 값은 `TRUE` 및 `FALSE`
* `background`. 청크의 배경색입니다. rgb 및 HTML 형식을 사용할 수 있으며, 기본값은 *"#F7F7F7"*.

## 추가 읽을거리

자세한 내용은 다음을 참조하세요

* [minted를 사용한 코드 강조 표시](/latex/ko/formatting/12-code-highlighting-with-minted.md)
* [LaTeX에서 색상 사용](/latex/ko/formatting/13-using-colors-in-latex.md)
* [LaTeX의 플롯](/latex/ko/field-specific/08-pgfplots-package.md)
* [이미지 삽입](/latex/ko/more-topics/27-inserting-images.md)
* [표](/latex/ko/figures-and-tables/01-tables.md)
* [이미지와 표 배치하기](/latex/ko/figures-and-tables/02-positioning-images-and-tables.md)
* [TikZ 패키지](/latex/ko/figures-and-tables/05-tikz-package.md)
* [수학 표현식](/latex/ko/mathematics/01-mathematical-expressions.md)
* [다음 **knitr** 웹 페이지](http://yihui.name/knitr/)
* [다음 **knitr** 패키지 매뉴얼](https://bitbucket.org/stat/knitr/downloads/knitr-manual.pdf)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/ko/more-topics/29-knitr.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
