简体   繁体   English

R-dplyr-如何更改行或行之间的分隔

[英]R - dplyr - How to mutate rows or divitions between rows

I found that dplyr is speedy and simple for aggregate and summarise data. 我发现dplyr快速,简单地汇总和汇总数据。 But I can't find out how to solve the following problem with dplyr. 但是我找不到使用dplyr解决以下问题的方法。

Given these data frames: 给定这些数据帧:

df_2017 <- data.frame(
  expand.grid(1:195,1:65,1:39), 
  value = sample(1:1000000,(195*65*39)),
  period = rep("2017",(195*65*39)),
   stringsAsFactors = F
)

df_2017 <- df_2017[sample(1:(195*65*39),450000),]

names(df_2017) <- c("company", "product", "acc_concept", "value", "period")

df_2017$company <- as.character(df_2017$company)
df_2017$product <- as.character(df_2017$product)
df_2017$acc_concept <- as.character(df_2017$acc_concept)
df_2017$value <- as.numeric(df_2017$value)

ratio_df <- data.frame(concept=c("numerator","numerator","numerator","denom", "denom", "denom","name"),
ratio1=c("1","","","4","","","Sales over Assets"),
ratio2=c("1","","","5","6","","Sales over Expenses A + B"), stringsAsFactors = F)

where the columns in df_2017 are: df_2017中的列为:

  • company = This is a categorical variable with companies from 1 to 195 company =这是公司从1到195的分类变量
  • product = This is a categorical, with home apliance products from 1 to 65. For example, 1 could be equal to irons, 2 to television, etc product =这是一个分类,家庭电器产品的取值范围是1到65。例如,1可以等于熨斗,2可以等于电视机,等等。
  • acc_concept = This is a categorical variable with accounting concepts from 1 to 39. For example, 1 would be equal to "Sales", 2 to "Total Expenses", 3 to Returns", 4 to "Assets, etc acc_concept =这是一个分类变量,其会计概念从1到39。例如,1等于“销售”,2等于“总费用”,3等于“收益”,4等于“资产”,等等。
  • value = This is a numeric variable, with USD from 1 to 100.000.000 value =这是一个数字变量,USD从1到100.000.000
  • period = Categorical variable. 期间 =分类变量。 Always 2017 永远2017

As the expand.grid implies, the combinations of company - product - acc_concept are never duplicated, but, It could happen that certains subjects have not every company - product - acc_concept combinations. 正如expand.grid所暗示的, 公司-产品-acc_concept的组合从不重复,但是,有可能某些主体没有每个公司-产品-acc_concept组合。 That's why the code line "df_2017 <- df_2017[sample(1:195*65*39),450000),]", and that's why the output could turn out into NA (see below). 这就是代码行“ df_2017 <-df_2017 [sample(1:195 * 65 * 39),450000),]”的原因,也是输出可能变为NA的原因(请参见下文)。

And where the columns in ratio_df are: ratio_df中的列在哪里:

  • Concept = which acc_concept corresponds to numerator, which one to denominator, and which is name of the ratio 概念 =哪个acc_concept对应于分子,哪个acc与分母,哪个是比率的名称
  • ratio1 = acc_concept and name for ratio1 比1 = acc_concept和名称比1
  • ratio2 = acc_concept and name for ratio2 ratio2 = acc_concept和ratio2的名称

I want to calculate 2 ratios (ratio_df) between acc_concept, for each product within each company. 我想为每个公司内的每个产品计算acc_concept之间的2个比率(ratio_df)。

For example: 例如:

I take the first ratio "acc_concepts" and "name" from ratio_df: 我从ratio_df中获取第一个比率“ acc_concepts”和“ name”:

num_acc_concept   <- ratio_df[ratio_df$concept == "numerator", 2]
denom_acc_concept <- ratio_df[ratio_df$concept == "denom", 2]
ratio_name        <- ratio_df[ratio_df$concept == "name", 2]

Then I calculate the ratio for one product of one company, just to show you want i want to do: 然后,我计算一家公司的一种产品的比率,只是为了表明您想要我要做的事情:

ratio1_value <- sum(df_2017[df_2017$company == 1 & df_2017$product == 1 & df_2017$acc_concept %in% num_acc_concept, 4]) / sum(df_2017[df_2017$company == 1 & df_2017$product == 1 & df_2017$acc_concept %in% denom_acc_concept, 4])

Output: 输出:

output <- data.frame(Company="1", Product="1", desc_ratio=ratio_name, ratio_value = ratio1_value, stringsAsFactors = F)

As i said before i want to do this for each product within each company 正如我之前所说,我想为每个公司的每个产品执行此操作

The output data.frame could be something like this (ratios aren't the true ones because i haven't done the calculations yet) : 输出data.frame可能是这样的(比率不是真正的比率,因为我还没有完成计算)

company    product   desc_ratio              ratio_value
1           1        Sales over Assets           0.9303675
1           2        Sales over Assets           1.30
1           3        Sales over Assets           Nan
1           4        Sales over Assets           Inf
1           5        Sales over Assets           2.32
1           6        Sales over Assets           NA
.
.
.
1           1        Sales over Expenses A + B   3.25
.
.
.
2           1        Sales over Assets          0.256

and so on... 等等...

  • NaN when ratio is 0 / 0 比率为0/0时的NaN
  • Inf when ratio is number / 0 比率为数字/ 0时的Inf
  • NA when there is no data for certain company and product. 当没有特定公司和产品的数据时,不适用。

I hope i have made myself clear this time :) 我希望这次我已经说清楚了:)

Is there any way to solve this row problem with dplyr? 有什么办法可以使用dplyr解决此行问题? Should I cast the df_2017 for mutating? 我应该将df_2017进行变异吗? In this case, which is the best way for casting? 在这种情况下,哪种铸造方法是最好的?

Any help would be welcome! 任何帮助都将受到欢迎!

This is one way of doing it. 这是一种方法。 At the end I timed the code on all of your records. 最后,我将代码计时到了所有记录上。

First create a function to create all the ratios. 首先创建一个函数来创建所有比率。 Do note, this function is only useful inside the dplyr code. 请注意,此功能仅在dpl​​yr代码内有用。

ratio <- function(data){
  result <- data.frame(desc_ratio = rep(NA, ncol(ratio_df) -1), ratio_value = rep(NA, ncol(ratio_df) -1))

  for(i in 2:ncol(ratio_df)){
    num   <- ratio_df[ratio_df$concept == "numerator", i]
    denom <- ratio_df[ratio_df$concept == "denom", i]
    result$desc_ratio[i-1] <- ratio_df[ratio_df$concept == "name", i]
    result$ratio_value[i-1] <- sum(ifelse(data$acc_concept %in% num, data$value, 0)) / sum(ifelse(data$acc_concept %in% denom, data$value, 0))
  }
  return(result)
}

Using dplyr, tidyr and purrr to put everything together. 使用dplyr,tidyr和purrr将所有内容放在一起。 First group by the data, nest the data needed for the function, run the function with a mutate on the nested data. 首先对数据进行分组,嵌套函数所需的数据,然后对嵌套数据进行mutate操作。 Drop the not needed nested data and unnest to get your wanted output. 删除不需要的嵌套数据和嵌套以获取所需的输出。 I leave the sorting up to you. 我将整理工作交给您。

library(dplyr)
library(purrr)
library(tidyr)
output <- df_2017 %>%
  group_by(company, product, period) %>% 
  nest() %>% 
  mutate(ratios = map(data, ratio)) %>% 
  select(-data) %>% 
  unnest

output

# A tibble: 25,350 x 5
   company product period desc_ratio                ratio_value
   <chr>   <chr>   <chr>  <chr>                           <dbl>
 1 103     2       2017   Sales over Assets               0.733
 2 103     2       2017   Sales over Expenses A + B       0.219
 3 26      26      2017   Sales over Assets               0.954
 4 26      26      2017   Sales over Expenses A + B       1.01 
 5 85      59      2017   Sales over Assets               4.14 
 6 85      59      2017   Sales over Expenses A + B       1.83 
 7 186     38      2017   Sales over Assets               7.85 
 8 186     38      2017   Sales over Expenses A + B       0.722
 9 51      25      2017   Sales over Assets               2.34 
10 51      25      2017   Sales over Expenses A + B       0.627
# ... with 25,340 more rows

Time it took to run this code on my machine measured with system.time : 在我的机器上运行此代码所花费的时间,该时间由system.time度量:

   user  system elapsed 
   6.75    0.00    6.81 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM