r - 添加行值然后在数据框之间划分
问题描述
我拥有的第一个数据框如下所示:
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 的结果。
解决方案
我不确定这是最优雅的解决方案:
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)
推荐阅读
- discord.js - Discord“无法向该用户发送消息”错误
- c++ - MSVC 无法返回可复制但无法移动的对象
- r - 在 cutpointr (R) 中设置两个手动切割点?
- ruby-on-rails - POSTGRES 问题:fe_sendauth:未提供密码
- docker - 在同一网络中从一个容器到另一个容器的 docker-compose api 调用
- c# - 如何测试 void 方法?
- python-3.x - 在 Spotify 上访问我的帐户并播放喜欢的歌曲 python
- session - CakePHP 4 - 查看助手 - 读取会话值时出错
- mysql - MySQL获取按日期设置的最新连续行
- matlab - 如何在matlab中过滤掉关于矩阵的数据集中的坏值?