> 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/texlive/ko/skills/r-knitr.md).

# R 코드(knitr)

Overleaf는 다음과의 통합 기능을 제공합니다 **knitr**, 이를 통해 LaTeX 문서에 R 코드를 추가하여 동적 출력을 생성할 수 있습니다.

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

{% code overflow="wrap" %}

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

LaTeX{} 문서에 R 명령을 입력할 수 있으며, 이는 처리되어 그 출력이 문서에 포함됩니다:

<<>>=
# 숫자 시퀀스 만들기
X = 2:10

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

@
\end{document}
```

{% endcode %}

![KnitrDemo1.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2F4rB1ItV9jgLU4dT6o3Hf%2FKnitrDemo1.png?alt=media\&token=5b2d4df8-8de9-4bdd-be61-0a3992026edf)

[이것을 열기 `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 청크에서 몇 가지 추가 옵션을 설정할 수 있습니다. 아래 예를 보세요:

{% code overflow="wrap" %}

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

LaTeX{} 문서에 R 명령을 입력할 수 있으며, 이는 처리되어 그 출력이 문서에 포함됩니다:

<<echo=FALSE, cache=TRUE>>=
# 숫자 시퀀스 만들기
X = 2:10

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

@
\end{document}
```

{% endcode %}

![KnitrDemo2.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2FHtobrK1TjY4SG4ax2BH5%2FScreenshot%202025-12-16%20143420.png?alt=media\&token=50675660-f20f-44d3-be60-fb91b8dbd255)

[이것을 열기 `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로 설정되면 해당 청크는 실행되지 않고, 그 청크에서 생성된 객체만 사용됩니다. 해당 청크의 데이터가 변경되지 않았다면 시간을 절약할 수 있습니다.

  <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p><em>cache=TRUE 옵션은 현재 Overleaf에서 지원되지 않지만, 로컬에서는 작동해야 합니다.</em></p></div>

다음을 보세요 [참조 가이드](https://learn.overleaf.com/learn/Knitr#Reference_guide) 에서 더 많은 옵션을 확인할 수 있습니다.

### 인라인 명령

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

{% code overflow="wrap" %}

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

LaTeX{} 문서에 R 명령을 입력할 수 있으며, 이는 처리되어 그 출력이 문서에 포함됩니다:

<<echo=FALSE, cache=TRUE>>=
# 숫자 시퀀스 만들기
X = 2:10

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

@

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

{% endcode %}

![KnitrDemo3.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2Fbyz9VKDCCPcoWHbznSJ4%2FScreenshot%202025-12-16%20143647.png?alt=media\&token=9d5ef4de-f413-4bf2-83c8-bf2171f50dee)

[이것을 열기 `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 문서에 플롯도 추가할 수 있습니다:

{% code overflow="wrap" %}

```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}
```

{% endcode %}

![KnitrDemo4.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2F5NI4NOJICjnYf8Z2Me1b%2FScreenshot%202025-12-16%20143811.png?alt=media\&token=d937786f-da22-4cbd-9adf-f277ec9f77c4)

[이것을 열기 `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"` 배치 매개변수입니다. 이는 다음에서 사용되는 것과 동일합니다 [그림 환경](https://learn.overleaf.com/learn/Positioning_images_and_tables#The_figure_environment).`fig.height=4, fig.width=4`그림의 너비와 높이입니다.`fig.cap="First plot"`그림 캡션입니다.

### 외부 R 스크립트

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

다음 R 코드가 다음 파일에 있다고 가정해 봅시다 `mycode.R` 이를 LaTeX 문서에 포함합니다:

```r
## ---- myrcode1
# 숫자 시퀀스 만들기
 X = 2:10

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

다음 줄에 주목하세요:

```r
## ---- myrcode1
```

와

```r
## ---- myrcode2
```

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

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

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

코드는 여기에서 표시되어야 합니다

<<myrcode2>>=

@
```

![KnitrDemo5.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2FPzKSGsFTMdhs9K8dE8Ny%2FKnitrDemo5.png?alt=media\&token=9c32c381-7621-4b7d-9d73-c1e7a0b6aac8)

첫 번째 청크는 출력되지 않으며, 명령으로 스크립트를 가져오는 데만 사용됩니다 `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=) .

### 참조 가이드

몇 가지 청크 옵션:

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


---

# 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/texlive/ko/skills/r-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.
