Получение R выводится на печать в ЛАТЕКС?

Поскольку None не единственная вещь, которую считают ложью.

if not False:
    print "False is false."
if not 0:
    print "0 is false."
if not []:
    print "An empty list is false."
if not ():
    print "An empty tuple is false."
if not {}:
    print "An empty dict is false."
if not "":
    print "An empty string is false."

False, 0, (), [], {} и "" все отличаются от [1 112], таким образом, Ваши два фрагмента кода не эквивалентны.

, Кроме того, рассмотрите следующее:

>>> False == 0
True
>>> False == ()
False

if object: не проверка равенства. 0, (), [], None, {}, и т.д. все отличающиеся друг от друга, но они весь оценивают ко Лжи.

Это - "волшебство" позади срывания выражений как:

foo = bar and spam or eggs

, который является стенографией для:

if bar:
    foo = spam
else:
    foo = eggs

, хотя действительно необходимо записать:

foo = spam if bar else egg
67
задан Helder S Ribeiro 11 December 2009 в 19:06
поделиться

4 ответа

Шейн отлично подходит, вам нужен Sweave. В конце концов.

Как новичок, вам лучше разделить задачи. Для этого сделайте следующее:

  1. откройте устройство: pdf ("sizes / myfile.pdf", height = 6, width = 6) .
  2. постройте свой объект R: plot (1:10, type = 'l', main = 'boring') - и помните, что решетке и ggplot требуется явная печать вокруг графика .
  3. важно: закройте устройство: dev.off () , чтобы завершить работу над файлом.
  4. необязательно: проверьте файл pdf.
  5. в LaTeX, используйте usepackage {graphicx} в в заголовке документа используйте
    \ includegraphics [width = 0. 98 \ textwidth] {figure / myfile} , чтобы включить рисунок, созданный ранее, и обратите внимание, что расширение файла необязательно.
  6. запустите его через pdflatex и наслаждайтесь.
56
ответ дан 24 November 2019 в 14:34
поделиться

I would recommend the tikzDevice package for producing output for inclusion in LaTeX documents:

http://cran.r-project.org/web/packages/tikzDevice/index.html

The tikzDevice converts graphics produced in R to code that can be interpreted by the LaTeX package tikz. TikZ provides a very nice vector drawing system for LaTeX. Some good examples of TikZ output are located at:

http://www.texample.net/

The tikzDevice may be used like any other R graphics device:

require( tikzDevice )

tikz( 'myPlot.tex' )

plot( 1, 1, main = '\\LaTex\\ is $\\int e^{xy}$' )

dev.off()

Note that the backslashes in LaTeX macros must be doubled as R interprets a single backslash as an escape character. To use the plot in a LaTeX document, simply include it:

\include{path/to/myPlot.tex}

The pgfSweave package contains Sweave functionality that can handle the above step for you. Make sure that your document contains \usepackage{tikz} somewhere in the LaTeX preamble.

http://cran.r-project.org/

The advantages of tikz() function as compared to pdf() are:

  • The font of labels and captions in your figures always matches the font used in your LaTeX document. This provides a unified look to your document.

  • You have all the power of the LaTeX typesetter available for creating mathematical annotation and can use arbitrary LaTeX code in your figure text.

Disadvantages of the tikz() function are:

  • It does not scale well to handle plots with lots of components. These are things such as persp() plots of large matricies. The shear number of graphic elements can cause LaTeX to slow to a crawl or run out of memory.

  • The package is currently flagged as beta. This means that the interface or functionality of the package is subject to change if the authors find a compelling reason to do so.

I should end this post by disclaiming that I am an author of both the tikzDevice and pgfSweave packages so my opinion may be biased. However, I have used both packages to produce several academic reports in the last year and have been very satisfied with the results.

59
ответ дан 24 November 2019 в 14:34
поделиться

Вы можете рассмотреть возможность использования Sweave . На веб-сайте Sweave (и в других местах) есть много отличной документации. Он имеет очень простой синтаксис: просто поместите свой код R между << >> = и @ .

Вот простой пример, который заканчивается , выглядящим так ]:

\documentclass[a4paper]{article}

\title{Sweave Example 1}
\author{Friedrich Leisch}

\begin{document}

\maketitle

In this example we embed parts of the examples from the
\texttt{kruskal.test} help page into a \LaTeX{} document:

<<>>=
data(airquality)
library(ctest)
kruskal.test(Ozone ~ Month, data = airquality)
@
which shows that the location parameter of the Ozone 
distribution varies significantly from month to month. Finally we
include a boxplot of the data:

\begin{center}
<<fig=TRUE,echo=FALSE>>=
boxplot(Ozone ~ Month, data = airquality)
@
\end{center}

\end{document}

Чтобы создать документ, вы можете просто вызвать R CMD Sweave file.Rnw или запустить Sweave (файл) из R.

22
ответ дан 24 November 2019 в 14:34
поделиться

Обновление

Я бы порекомендовал разбить XML на отношения и выполнить поиск и объединение в результирующем отношении, ориентируясь на набор, а не процедурный способ поиска определенных узлов в XML. Вот простой XML-запрос, который удаляет интересующие узлы и атрибуты:

select x.value(N'../../../../@stepId', N'int') as StepID
  , x.value(N'../../@id', N'int') as ComponentID
  , x.value(N'@nom',N'nvarchar(100)') as Nom
  , x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)

Однако, если вы должны использовать XPath, который извлекает именно интересующее значение:

select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
       variables/variable[@nom="Enabled"]') t(x)

Если stepID и идентификатор компонента являются столбцами, а не переменными, вам следует использовать sql: column () вместо sql: variable в фильтрах XPath. См. Связывание реляционных данных внутри данных XML . http://r-forge.r-project.org/projects/tikzdevice/ -- tikz output from r and http://www.rforge.net/pgfSweave/ код tikz через sweave.

Использование tikz даст вам вид, соответствующий остальной части вашего документа, плюс будет использован латекс для набора всех текст в ваших графиках.

РЕДАКТИРОВАТЬ Получение LaTeX в R-графики

3
ответ дан 24 November 2019 в 14:34
поделиться
Другие вопросы по тегам:

Похожие вопросы: