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

Содержимое удалено Содержимое добавлено
→‎Циклы "for": обновление данных
Implicit loops
Строка 85:
</pre>
 
=== ImplicitНеявные loopsциклы ===
Циклы обычно медленны и лучше избегать их по возможности.
 
* Функция <tt>apply()</tt> может применить функцию к элементу матрицы или массиву. Чтобы применить к строке, нужно вторым параметром отдать цифру <code>1</code>; чтобы применить к столбцу - <code>2</code>.
Loops are generally slow and it is better to avoid them when it is possible.
* <tt>apply()</tt> can apply a function to elements of a matrix or an array. This may be the rows of a matrix (1) or the columns (2).
* <tt>lapply()</tt> applies a function to each column of a dataframe and returns a list. <tt>sapply()</tt> is similar but the output is simplified. It may be a vector or a matrix depending on the function.
* <tt>tapply()</tt> applies the function for each level of a factor.
 
<pre width = 80>
> N <- 10
Строка 99 ⟶ 95 :
> y <- 1 + x1 + x2 + male + rnorm(N)
> mydat <- data.frame(y,x1,x2,male)
> lapplyapply(mydat,1,mean) # returnsприменяет функцию к aкаждой listстроке
[1] 1.1654 2.8347 -0.9728 0.6512 -0.0696 3.9206 -0.2492 3.1060 2.0478 0.5116
> apply(mydat,2,mean) # применяет функцию к каждому столбцу
y x1 x2 male
3.2468 0.1415 1.2900 0.5000
</pre>
* Функция <tt>lapply()</tt> применяет функцию к каждому столбцу структуры и возвращает список.
<pre width = 80>
> lapply(mydat,mean) # возвращает список
$y
[1] 3.247
Строка 111 ⟶ 115 :
$male
[1] 0.5
</pre>
 
* Функция <tt>sapply()</tt> похожа, но не возвращает ничего на экран. Могут существовать векторы или матрицы зависящие от этой функции.
> sapply(mydat,mean) # returns a vector
<pre width = 80>
> sapply(mydat,mean) # returnsвозвращает a vectorвектор
y x1 x2 male
3.2468 0.1415 1.2900 0.5000
</pre>
> apply(mydat,1,mean) # applies the function to each row
* Функция <tt>tapply()</tt> применяет функцию к каждому уровню factor-а.
[1] 1.1654 2.8347 -0.9728 0.6512 -0.0696 3.9206 -0.2492 3.1060 2.0478 0.5116
<pre width = 80>
> apply(mydat,2,mean) # applies the function to each column
> tapply(mydat$y,mydat$male,mean) # применяет функцию к каждому уровню factor-а.
y x1 x2 male
3.2468 0.1415 1.2900 0.5000
> tapply(mydat$y,mydat$male,mean) # applies the function to each level of the factor
0 1
1.040 5.454