Telegram Group & Telegram Channel
Рекурсивные операции в R: Магия функции accumulate()

accumulate() из пакета purrr - потрясающий инструмент для выполнения рекурсивных вычислений в R. Давайте рассмотрим три последовательных примера от простого к сложному.

1. Пример 1: Накопительная сумма

library(purrr)

# Простейший пример накопления суммы
numbers <- 1:5
result <- accumulate(numbers, `+`)
# Результат: [1] 1 3 6 10 15


Как это работает?:

● Начинает с первого элемента (1)
● Каждый следующий шаг - сумма предыдущего накопленного результата и текущего элемента
● 1 → (1+2=3) → (3+3=6) → (6+4=10) → (10+5=15)

Пример 2: Генерация последовательности Фибоначчи

fibonacci <- accumulate(1:10, function(acc, _) {
c(acc[2], sum(acc))
}, .init = c(0, 1))

# Результат: последовательность Фибоначчи
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]


Детали реализации:

.init устанавливает начальное состояние
● На каждой итерации берем второй элемент и сумму
● Создаем классическую последовательность Фибоначчи

Пример 3: Сложная трансформация данных

library(dplyr)

# Имитация сложного бизнес-процесса
transactions <- list(
list(amount = 100, tax_rate = 0.1),
list(amount = 200, tax_rate = 0.15),
list(amount = 150, tax_rate = 0.12)
)

total_calculation <- accumulate(transactions, function(acc, transaction) {
list(
total_amount = acc$total_amount + transaction$amount,
total_tax = acc$total_tax + (transaction$amount * transaction$tax_rate),
processed_count = acc$processed_count + 1
)
}, .init = list(
total_amount = 0,
total_tax = 0,
processed_count = 0
))

# Финальный результат в последнем элементе
final_result <- total_calculation[[length(total_calculation)]]


Сценарий:

● Накапливаем статистику по транзакциям
● Считаем общую сумму, налоги, количество обработанных записей
● Используем аккумуляцию для последовательной обработки

————————————
В пакете purrr помимо accumulate() есть множество других полезных функционалов, которые могут заменить вам циклы for, и сделать ваш код более читабельным и оптимизированным.

Тему циклов и функционалов я подробно рассматривал в бесплатном курсе "Циклы и функционалы в языке R", так что если есть желание погрузится в эту тему то велкам!

#заметки_по_R



group-telegram.com/R4marketing/1332
Create:
Last Update:

Рекурсивные операции в R: Магия функции accumulate()

accumulate() из пакета purrr - потрясающий инструмент для выполнения рекурсивных вычислений в R. Давайте рассмотрим три последовательных примера от простого к сложному.

1. Пример 1: Накопительная сумма

library(purrr)

# Простейший пример накопления суммы
numbers <- 1:5
result <- accumulate(numbers, `+`)
# Результат: [1] 1 3 6 10 15


Как это работает?:

● Начинает с первого элемента (1)
● Каждый следующий шаг - сумма предыдущего накопленного результата и текущего элемента
● 1 → (1+2=3) → (3+3=6) → (6+4=10) → (10+5=15)

Пример 2: Генерация последовательности Фибоначчи

fibonacci <- accumulate(1:10, function(acc, _) {
c(acc[2], sum(acc))
}, .init = c(0, 1))

# Результат: последовательность Фибоначчи
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]


Детали реализации:

.init устанавливает начальное состояние
● На каждой итерации берем второй элемент и сумму
● Создаем классическую последовательность Фибоначчи

Пример 3: Сложная трансформация данных

library(dplyr)

# Имитация сложного бизнес-процесса
transactions <- list(
list(amount = 100, tax_rate = 0.1),
list(amount = 200, tax_rate = 0.15),
list(amount = 150, tax_rate = 0.12)
)

total_calculation <- accumulate(transactions, function(acc, transaction) {
list(
total_amount = acc$total_amount + transaction$amount,
total_tax = acc$total_tax + (transaction$amount * transaction$tax_rate),
processed_count = acc$processed_count + 1
)
}, .init = list(
total_amount = 0,
total_tax = 0,
processed_count = 0
))

# Финальный результат в последнем элементе
final_result <- total_calculation[[length(total_calculation)]]


Сценарий:

● Накапливаем статистику по транзакциям
● Считаем общую сумму, налоги, количество обработанных записей
● Используем аккумуляцию для последовательной обработки

————————————
В пакете purrr помимо accumulate() есть множество других полезных функционалов, которые могут заменить вам циклы for, и сделать ваш код более читабельным и оптимизированным.

Тему циклов и функционалов я подробно рассматривал в бесплатном курсе "Циклы и функционалы в языке R", так что если есть желание погрузится в эту тему то велкам!

#заметки_по_R

BY R4marketing | канал Алексея Селезнёва | Язык R




Share with your friend now:
group-telegram.com/R4marketing/1332

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

Overall, extreme levels of fear in the market seems to have morphed into something more resembling concern. For example, the Cboe Volatility Index fell from its 2022 peak of 36, which it hit Monday, to around 30 on Friday, a sign of easing tensions. Meanwhile, while the price of WTI crude oil slipped from Sunday’s multiyear high $130 of barrel to $109 a pop. Markets have been expecting heavy restrictions on Russian oil, some of which the U.S. has already imposed, and that would reduce the global supply and bring about even more burdensome inflation. Channels are not fully encrypted, end-to-end. All communications on a Telegram channel can be seen by anyone on the channel and are also visible to Telegram. Telegram may be asked by a government to hand over the communications from a channel. Telegram has a history of standing up to Russian government requests for data, but how comfortable you are relying on that history to predict future behavior is up to you. Because Telegram has this data, it may also be stolen by hackers or leaked by an internal employee. Just days after Russia invaded Ukraine, Durov wrote that Telegram was "increasingly becoming a source of unverified information," and he worried about the app being used to "incite ethnic hatred." On Telegram’s website, it says that Pavel Durov “supports Telegram financially and ideologically while Nikolai (Duvov)’s input is technological.” Currently, the Telegram team is based in Dubai, having moved around from Berlin, London and Singapore after departing Russia. Meanwhile, the company which owns Telegram is registered in the British Virgin Islands. "We as Ukrainians believe that the truth is on our side, whether it's truth that you're proclaiming about the war and everything else, why would you want to hide it?," he said.
from it


Telegram R4marketing | канал Алексея Селезнёва | Язык R
FROM American