首页 > 解决方案 > 添加行值然后在数据框之间划分

问题描述

我拥有的第一个数据框如下所示:

ID 2016 2017
1  5    6
2  15   20
3  10   10

第二个数据框是相同的,但具有不同的值:

ID 2016 2017
1  20   30
2  50   40
3  10   15

我想在每个表中添加 ID 号 1 和 3,然后将第一个数据帧除以新数据帧中的第二个数据帧。我还想将第一个表中的 ID 2 除以第二个表中的 ID 2。最后,我希望新数据框的行名包含这些计算的结果,所以:

Type 2016 2017
A    0.5  0.36
B    0.3  0.5

A 行是 ID 1 和 3 的结果,而 B 行是 ID 2 的结果。

标签: rsumaggregatedivide

解决方案


我不确定这是最优雅的解决方案:


library(dplyr)
library(purrr)
library(tibble)

df1 <- structure(list(`2016` = c(5L, 15L, 10L), `2017` = c(6L, 20L, 10L)), class = "data.frame", row.names = c(NA, -3L))

df2 <- structure(list(`2016` =  c(20L, 50L, 10L), `2017` = c(30L, 40L, 15L)), class = "data.frame", row.names = c(NA, -3L))

# add ID to each dataframe

df1  %>%  
  rowid_to_column(var = "ID")
#>   ID 2016 2017
#> 1  1    5    6
#> 2  2   15   20
#> 3  3   10   10

要根据您的要求创建第三个数据框,我不确定我们是否需要 ID 列,所以......


#A little function to prepare each data frame

df_Type <- function(x){

  x %>% 
  mutate(Type = c("A", "B", "A")) %>% 
  group_by(Type) %>% 
  summarise_all(sum)

}


# the function could be place in the list below to avoid additional objects but it makes it clear what is happening

df1_Type <- df_Type(df1)

df2_Type <- df_Type(df2)

> df2_Type
# A tibble: 2 x 3
  Type  `2016` `2017`
  <chr>  <int>  <int>
1 A         30     45
2 B         50     40

#dividing one data frame by the other

list(select_if(df1_Type, is.numeric),
     select_if(df2_Type, is.numeric)) %>% 
pmap_dfr(function(x, y) x / y) %>% 
bind_cols(df1_Type[, 1]) %>% 
  select(Type, everything())

#> # A tibble: 2 x 3
#>   Type  `2016` `2017`
#>   <chr>  <dbl>  <dbl>
#> 1 A        0.5  0.356
#> 2 B        0.3  0.5

reprex 包于 2020-05-21 创建(v0.3.0)


推荐阅读