如何基于数据帧的列将Reduce()应用于组?

问题描述 投票:1回答:1

我几天前发布了一个问题:How to create a "dynamic" column in R?(参考,以便您可以更好地理解我对此的要求)以创建“动态”列,而解决方案是使用Reduce()函数。现在,我希望基本上执行相同的操作(以上一行作为参考来计算余额的变化),但要根据数据帧的子集按特定列进行过滤。简而言之,我只想对组执行相同的计算,所以我将X值作为组A,B和C的起始资本,余额的变化将“重置”为组的起始资本。每组。

我知道上面的解释还不清楚,所以这是我想要实现的目标的快速简化版本:

class <- c("a", "a", "b", "b", "c", "c")
profit <- c(10, 15, -5, -6, 20, 5)
change <- profit / 1000
balance <- c(1010, 1025, 1020, 1014, 1036, 1039)

data <- data.frame(class, profit, change, balance)

a <- data %>% filter(class == "a")
b <- data %>% filter(class == "b")
c <- data %>% filter(class == "c")
start_capital = 1000

a_bal <- Reduce(function(x, y) x + x*y, a$change, init = start_capital, accumulate = TRUE)[-1]
a <- mutate(a, balance = a_bal, 
               profit = balance - (balance / (1 + change)))

b_bal <- Reduce(function(x, y) x + x*y, b$change, init = start_capital, accumulate = TRUE)[-1]
b <- mutate(b, balance = b_bal, 
            profit = balance - (balance / (1 + change)))            

c_bal <- Reduce(function(x, y) x + x*y, c$change, init = start_capital, accumulate = TRUE)[-1]
c <- mutate(c, balance = c_bal, 
            profit = balance - (balance / (1 + change)))

data <- bind_rows(a, b, c)

  class profit change balance
1     a  10.00  0.010 1010.00
2     a  15.15  0.015 1025.15
3     b  -5.00 -0.005  995.00
4     b  -5.97 -0.006  989.03
5     c  20.00  0.020 1020.00
6     c   5.10  0.005 1025.10

显然,有一种更有效的方法,但这就是我要寻找的。我解决这个问题的方法是创建一个函数,该函数将要应用计算的数据框和类作为输入,并输出该组具有修改后值的数据框,然后使用一些apply函数执行所有组的操作。但是在开始创建该功能之前,我想问一下是否有一种方法可以对现有功能进行此操作。我当时正在考虑在管道运算符上使用group_by(),但是由于Reduce()并非来自tidyverse库,因此无法使用。

r dataframe data-wrangling
1个回答
1
投票

只需进行分组操作:

library(dplyr)
library(purrr)

data %>%
  group_by(class) %>%
  mutate(balance = accumulate(.f = ~ .x + .x * .y, change, .init = start_capital)[-1])

# A tibble: 6 x 5
# Groups:   class [3]
  class profit change balance     y
  <fct>  <dbl>  <dbl>   <dbl> <dbl>
1 a         10  0.01     1010 1010 
2 a         15  0.015    1025 1025.
3 b         -5 -0.005    1020  995 
4 b         -6 -0.006    1014  989.
5 c         20  0.02     1036 1020 
6 c          5  0.005    1039 1025.

请注意,您会误解并且不仅限于将tidyverse函数与tidyverse一起使用。您可以使用任何合适的功能。您使用Reduce()的函数很好,尽管为了紧凑起见,我将其交换为accumulate(),这与Reduce()的整字等效,并且累计参数为TRUE。

data %>%
  group_by(class) %>%
  mutate(balance = Reduce(function(x, y) x + x * y, change, init = start_capital, accumulate = TRUE)[-1])

或在基数R中使用ave()

ave(data$change, data$class, FUN = function(v) Reduce(function(x, y) x + x * y, v, init = start_capital, accumulate = TRUE)[-1])
© www.soinside.com 2019 - 2024. All rights reserved.