Язык программирования R/Введение: различия между версиями

Содержимое удалено Содержимое добавлено
Строка 51:
* [http://google-styleguide.googlecode.com/svn/trunk/google-r-style.html Google’s R Style Guide]: набор правил для программистов на '''R'''
 
== Простые примеры ==
== Sample Session ==
 
'''R''' может быть использован как калькулятор и предоставляет возможности для любых простых вычислений.
R can be used as a simple calculator and we can perform any simple computation.
 
<pre WIDTH=80 >
> # Простой пример
> # Sample Session
> # Это комментарий
> # This is a comment
>
> 2 # printпечатает a numberчисло
[1] 2
> 2+3 # производит простое сложение
> 2+3 # perform a simple calculation
[1] 5
> log(2)
Строка 67:
</pre>
 
Также возможно сохранять числовые и строковые объекты.
We can also store numeric or string objects.
<pre width=80>
> x <- 2 # storeсохраняем an objectобъект
> x # выводим этот объект
> x # print this object
[1] 2
> (x <- 3) # storeсохраняем andи printвыводим an objectобъект
[1] 3
>
> x <- "Hello" # storeсохраняем aстроковый string objectобъект
> x
[1] "Hello"
</pre>
 
Также можно сохранять векторы.
We can also store vectors.
<pre width=80>
> Height <- c(168, 177, 177, 177, 178, 172, 165, 171, 178, 170) #store aСохраняем vectorвектор
> Height # printвыводим the vectorвектор
[1] 168 177 177 177 178 172 165 171 178 170
>
> Height[2] # Выводим второй элемент вектора (нумерация элементов происходит с единицы)
> Height[2] # Print the second component
[1] 177
> Height[2:5] # PrintВыводим the secondвторой, the 3rdтретий, theчетвёртый 4thи andпятый 5thэлементы componentвектора
[1] 177 177 177 178
>
> (obs <- 1:10) # DefineОпределяем aвектор vectorкак asпоследовательность a(от sequence (1 toдо 10)
[1] 1 2 3 4 5 6 7 8 9 10
>
> Weight <- c(88, 72, 85, 52, 71, 69, 61, 61, 51, 75)
>
> BMI <- Weight/((Height/100)^2) # PerformsПроизводим aпростые simpleвычисления calculationс using vectorsвекторами
> BMI
[1] 31.17914 22.98190 27.13141 16.59804 22.40879 23.32342 22.40588 20.86112
[9] 16.09645 25.95156
</pre>
WeТакже canможно alsoполучать describeданные theо vectorвекторе withпри помощи <tt>length()</tt>, <tt>mean()</tt> andи <tt>var()</tt>.:
<pre width=80>
> length(Height)
[1] 10
> mean(Height) # ComputeВычисляем theсреднее sample meanарифметическое
[1] 173.3
> var(Height)
[1] 22.23333
</pre>
Можно определить матрицу:
We can also define a matrix.
<pre width=80>
> M <- cbind(obs,Height,Weight,BMI) # CreateСоздаём a matrixматрицу
> typeof(M) # GiveПолучаем theтип type of the matrixматрицы
[1] "double"
> class(M) # GiveПолучаем theкласс class of an objectобъекта
[1] "matrix"
> is.matrix(M) # Check ifПроверяем, является ли M is a matrixматрицей
[1] TRUE
> is.vector(M) # M isне not a vectorвектор
[1] FALSE
> dim(M) # DimensionsРазмерности of a vectorвектора
[1] 10 4
</pre>
 
WeМожно canнарисовать plot the dataданные usingиспользуя <tt>plot()</tt>.:
<pre width=80>
> plot(Height,Weight,ylab="WeightВес",xlab="HeightВысота",main="CorpulenceОжирение")
</pre>
 
Можно определить структуру данных:
We can define a dataframe.
<pre width=80>
> mydat <- data.frame(M) # CreatesСоздаём a dataframeструктуру
> names(mydat) # GiveДаём theимена namesкаждой of each variableпеременной
[1] "obs" "Height" "Weight" "BMI"
> str(mydat) # giveвыводим theструктуру structure of your dataданных
'data.frame': 10 obs. of 4 variables:
$ obs : num 1 2 3 4 5 6 7 8 9 10
Строка 142:
$ BMI : num 31.2 23 27.1 16.6 22.4 ...
>
> View(mydat) # LookСмотрим atна your dataданные
>
> summary(mydat) # DescriptiveНаглядная Statisticsстатистика
obs Height Weight BMI
Min. : 1.00 Min. :165.0 Min. :51.00 Min. :16.10
Строка 155:
</pre>
 
Вы можете сохранить сессию '''R''' (все объекты в памяти) и загрузить сессию.
You can save an R session (all the objects in memory) and load the session.
 
<pre width=80>
Строка 162:
</pre>
 
Можно определить рабочую дирректорию. Внимание, для пользователей Windows: '''R''' использует прямой, а не обратный слеш, в именах дирректорий.
We can define a working directory. Note for Windows users : R uses slash in the directory instead of antislash.
<pre width=80>
> setwd("~/Desktop") # SetsУстанавливаем workingрабочую directoryдирректорию (character string enclosed in "...")
> getwd() # ReturnsВозвращаем currentтекущую workingрабочую directoryдирректорию
[1] "/Users/username/Desktop"
> dir() # Выводим список содержимого рабочей дирректории
> dir() * Lists the content of the working directory
</pre>
 
В '''R''' существуют спецсимволы:
There are some special characters in R
* <tt>NA</tt> : Not Available (ieто missingесть valuesпропущенные значения)
* <tt>NaN</tt> : Not a Number (eg"не число", например, неопределённость 0/0)
* <tt>Inf</tt>: InfinityБесконечность
* <tt>-Inf</tt> : MinusМинус Infinityбесконечность.
For instanceВыражение 0 dividedделить byна 0 gives aдаёт <tt>NaN</tt>, butно 1 dividedделить byна 0 givesдаёт <math>+\infty</math>
<pre width=80>
> 0/0
Строка 183:
</pre>
 
WeИз can'''R''' exitможно Rвыйти usingиспользуя <tt>q()</tt>. TheАргумент <tt>no</tt> argumentобозначает, specifies that the Rчто sessionсессию isсохранять notне savedнужно.
<pre width=80>
q("no")
</pre>
 
 
== Data types ==