[英]purrr: Split dataframe and run map on several columns
I have a large dataframe and I need to calculate values for combinations of columns based on an id column. 我的数据框很大,我需要根据id列计算列组合的值。 I would like to do so within a
tidyverse
framework and I can get there, but it does not seem to be very elegant and error-prone. 我想在一个
tidyverse
框架内做到这一点,但我可以到达那儿,但是它似乎不是很优雅且容易出错。 Perhaps someone could help me out. 也许有人可以帮助我。
Here is a minimal working example similar to the actual data. 这是一个类似于实际数据的最小工作示例。
library(tidyverse)
df <- tibble(
id_combo = c("A_A1", "A_A1", "A_A2", "A_A2", "A_A2"),
f1 = runif(5),
f2 = runif(5),
f3 = runif(5),
b1 = runif(5),
b2 = runif(5),
b3 = runif(5)
)
f1_f2 <- df %>%
split(.$id_combo) %>%
map_dbl(., ~var(log(.$f1))+var(log(.$f2)))
f1_f3 <- df %>%
split(.$id_combo) %>%
map_dbl(., ~var(log(.$f1))+var(log(.$f2))+var(log(.$f3)))
f1_b2 <- df %>%
split(.$id_combo) %>%
map_dbl(., ~var(log(.$f1))+var(log(.$f2))+
var(log(.$b1))+var(log(.$b2)))
f1_b3 <- df %>%
split(.$id_combo) %>%
map_dbl(., ~var(log(.$f1))+var(log(.$f2))+var(log(.$f3))+
var(log(.$b1))+var(log(.$b2))+var(log(.$b3)))
var_sum_df <- tibble(id_combo = names(f1_f2),f1_f2, f1_f3, f1_b2, f1_b3)
What I hope to achieve is to run the map_dbl
function (or a sensible equivalent) after split(.$id_combo)
, specifying the columns on the fly. 我希望实现的是在
split(.$id_combo)
之后运行map_dbl
函数(或明智的等效split(.$id_combo)
,并动态指定列。
I am sure this would be possible, but my R knowledge is not yet advanced enough to figure out myself. 我相信这是有可能的,但是我的R知识还不够先进,无法弄清楚自己。
I am not sure if I understood the question correctly, but is this what you are looking for? 我不确定我是否正确理解了这个问题,但这是您要找的东西吗?
library(tidyverse)
df %>% group_by(id_combo) %>%
summarise_all(~var(log(.x))) %>%
mutate(f1_f2 = f1 + f2,
f1_f3 = f1_f2 + f3,
f1_b2 = f1_f3 + b1 + b2,
f1_b3 = f1_b2 + b3) %>%
select(id_combo, contains("_"))
# A tibble: 2 x 5
id_combo f1_f2 f1_f3 f1_b2 f1_b3
<chr> <dbl> <dbl> <dbl> <dbl>
1 A_A1 0.0582 0.0701 1.24 6.89
2 A_A2 2.43 2.57 3.50 3.76
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.